Reputation: 155
let array1 = [{id: 1, name:'xyz', inclusions: [43,23,12]},{id: 2, name: 'abc',inclusions:[43, 12, 90]},{id: 3, name:'pqr', inclusions: [91]}];
let array 2 = [43, 12, 90, 45];
Now i want to get all the elements of array1, which has inclusions present in array2.
So output would be something:
result = [{id: 1, name:'xyz', inclusions: [43,23,12]},{id: 2, name: 'abc',inclusions:[43, 12, 90]}
I am using two for loops, which i don't want. How can i achieve it using filter and includes.
Upvotes: 1
Views: 47
Reputation: 370619
Filter by whether .some
of the items of the object being iterated over are included:
let array1 = [{id: 1, name:'xyz', inclusions: [43,23,12]},{id: 2, name: 'abc',inclusions:[43, 12, 90]},{id: 3, name:'pqr', inclusions: [91]}];
let array2 = [43, 12, 90, 45];
const filtered = array1.filter(({ inclusions }) => inclusions.some(
num => array2.includes(num)
));
console.log(filtered);
Upvotes: 1