0

I want to filter the objects from array:

let x = [{a: 100, categories: [22, 23 ] 

}, {a: 101, categories: [20, 21 ] }];
let y = [22]; //can be multiple

let result = x.filter(i => y.includes(i.categories)  );
console.log(result);
// result = []

Expected Output:

[{a: 100, categories: [22, 23 ]}]

but I get empty array.

2
  • What is the expected output? Can you clarify a little better what is your question? Commented Sep 9, 2019 at 16:22
  • ah sorry.. i have already edited my questions Commented Sep 9, 2019 at 16:29

3 Answers 3

2

Use some to see if some of the items are in the categories array.

let x = [{a: 100, categories: [22, 23 ] }, {a: 101, categories: [20, 21 ] }];
let y = [22]; //can be multiple

let result = x.filter(i => y.some(a => i.categories.includes(a)));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You're checking whether the entire array i.categories is in y, use Array.prototype.some to check if any element of i.categories is in y:

let x = [{a: 100, categories: [22, 23 ] }, {a: 101, categories: [20, 21 ] }];
let y = [22]; //can be multiple

let result = x.filter(i => y.some(x => i.categories.includes(x)));

console.log(result);

Comments

0

If x, .categories, or y is significantly large, you can achieve a significant speed improvement by first converting y to a Set. Set.prototype.has provides much faster lookup times, O(1), compared to Array.prototype.includes, O(n) -

const x =
  [ { a: 100, categories: [ 22, 23 ] }
  , { a: 101, categories: [ 20, 21 ] }
  , { a: 102 }
  ]
  
const y =
  [ 22 ] //can be multiple

const ySet =
  new Set(y) // has O(1) lookup

let result =
  x.filter(({ categories = [] }) =>
    categories.some(c => ySet.has(c)) // <-- use set lookup
  )
  
console.log(result)
// [ { a: 100, categories: [ 22, 23 ] } ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.