filter the elements of one array wrt to another array in js

Viewed 40
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.

1 Answers

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);

Related