I have an array object:
[
{ id:1, name: \'Pedro\'},
{ id:2, name: \'Miko\'},
{ id:3, name: \'Bear\'},
{ id:4, name: \'Teddy\'},
{ id:5, n
Using filter
and indexOf
will do the trick:
var filteredArray = dataArray.filter(function(obj) {
return idsArray.indexOf(obj.id) > -1;
});
However, indexOf
has linear performance, and it will be called lots of times.
In ES6 you can use a set instead, whose has
call has sublinear performance (on average):
var idsSet = new Set(idsArray),
filteredArray = dataArray.filter(obj => idsSet.has(obj.id));
Assuming the toString
method of your ids is injective, you can achieve something similar in ES5:
var idsHash = Object.create(null);
idsArray.forEach(function(id) {
idsHash[id] = true;
});
var filteredArray = dataArray.filter(function(obj) {
return idsHash[obj.id];
});