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:)
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:
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. AndArray.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'sid
is not present in theids
array.You can use .filter