Reputation: 310
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.
Upvotes: 0
Views: 63
Reputation: 135227
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 ] } ]
Upvotes: 0
Reputation: 36311
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);
Upvotes: 2
Reputation: 22776
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);
Upvotes: 1