Filter the original array of objects by array of i

2019-04-11 23:26发布

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:)

2条回答
戒情不戒烟
2楼-- · 2019-04-11 23:32

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-11 23:44

You can use .filter

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

// should give you [{id: 1, name: 'a'}]
查看更多
登录 后发表回答