Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter the original array of objects by array of ids

I have two arrays:

array a:

var a = [
  {
    id: 1,
    name: 'a'
  },
  {
    id: 2,
    name: 'b'
  },
  {
    id: 3,
    name: 'c'
  }
];

array ids:

var ids = [1];

I want to array a filtered by array ids, result i wanted:

var a = [
  {
    id: 1,
    name: 'a'
  }
];

The most important thing is i want the change on the original array, rather than return a new array.

underscore solution is better:)

like image 955
huan feng Avatar asked May 09 '15 02:05

huan feng


2 Answers

You can use .filter

a = a.filter(function(el){ 
    return ~ids.indexOf(el.id)
});

// should give you [{id: 1, name: 'a'}]
like image 76
bruchowski Avatar answered Nov 14 '22 21:11

bruchowski


Today I tried to solve similar task (filtering the original array of objects without creating a new array) and this is what I came up with:

const a = [{ id: 1, name: 'a'}, { id: 2, name: 'b'}, { id: 3, name: 'c'}];
const ids = [1];

Array.from(Array(a.length).keys()).reverse().forEach(index =>
  !ids.some(id => id === a[index].id) && a.splice(index, 1)
);

console.log(a); // [{ id: 1, name: 'a'}]

The point is that we need to loop back through the original array to be able to use Array.prototype.splice, but I didn't want the for-loop, I wanted to have ES6 one-liner. And Array.from(Array(a.length).keys()).reverse() gives me a list of reversed indexes of the original array. Then I want to splice the original array by current index only if the corresponding item's id is not present in the ids array.

like image 36
dhilt Avatar answered Nov 14 '22 23:11

dhilt