Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript filter array by data from another

I have an array object:

[
    { id:1, name: 'Pedro'},
    { id:2, name: 'Miko'},
    { id:3, name: 'Bear'},
    { id:4, name: 'Teddy'},
    { id:5, name: 'Mouse'}
]

And I have an array with ids [1, 3, 5],

How can I filter the array object to leave records only with id's from the second one?

like image 210
Serhio g. Lazin Avatar asked Sep 03 '15 13:09

Serhio g. Lazin


People also ask

How do you filter an array of objects in JavaScript based on another array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you filter an array from all elements of another array object?

You can use the filter() method to find the elements of the first array which are not in the second array. Using jQuery. With jQuery, you can use the . not() method to get the difference.

What does .filter do in JavaScript?

Definition and Usage. The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.


1 Answers

If Array.includes() is supported, you can use it with Array.filter() to get the items:

const array = [
  { id: 1, name: 'Pedro'},
  { id: 2, name: 'Miko'},
  { id: 3, name: 'Bear'},
  { id: 4, name: 'Teddy'},
  { id: 5, name: 'Mouse'}
];

const filterArray = [1,3,5];

const result = array.filter(({ id }) => filterArray.includes(id));

console.log(result);

If includes is not supported, you can use Array.indexOf() instead:

var array = [
  { id: 1, name: 'Pedro'},
  { id: 2, name: 'Miko'},
  { id: 3, name: 'Bear'},
  { id: 4, name: 'Teddy'},
  { id: 5, name: 'Mouse'}
];

var filterArray = [1,3,5];

var result = array.filter(function(item) {
    return filterArray.indexOf(item.id) !== -1;
});

console.log(result);
like image 70
Ori Drori Avatar answered Oct 04 '22 06:10

Ori Drori