How to Filter a JavaScript Array of Objects Using Another Array of Objects?

Estimated read time 1 min read

You can filter a JavaScript array of objects by using the Array.prototype.filter() method and comparing properties of objects in the two arrays. You can use the Array.prototype.some() method to check if an element in the filter array exists in the original array.

Here’s an example:

const originalArray = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'},
  {id: 3, name: 'Jim'},
  {id: 4, name: 'Jessica'}
];

const filterArray = [
  {id: 2},
  {id: 4}
];

const filteredArray = originalArray.filter(obj =>
  filterArray.some(filterObj => filterObj.id === obj.id)
);

console.log(filteredArray); 
// Output: [{id: 2, name: 'Jane'}, {id: 4, name: 'Jessica'}]

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply