Underscore JS difference on array and array with objects

纵然是瞬间 提交于 2019-12-25 07:14:06

问题


I'm having an array with certain numbers and an array with certain objects, looking like this:

var names = [
  { id: 1, name: 'Alex'},
  { id: 2, name: 'John'},
  { id: 3, name: 'Mary'}
];

var blocked_ids = [1, 2];

Now I would like to remove the objects with the blocked_ids from the names array. So the result would be this:

[
  { id: 3, name: 'Mary'}
]

As you can see the objects with id 1 and 2 are gone, because the array "blocked_ids" contained these numbers. If it where just two arrays, i could use _.difference(), but now I have to compare the blocked_ids with the id's inside the array's objects. Anyone knows how to do this?


回答1:


You could do this by using the _.reject method.

For example:

_.reject(names, function(name) {
    return blockedIds.indexOf(name.id) > -1;
});

See this JSFiddle.




回答2:


Assuming block-ids you have given is an array of Ids, You can use reject like bellow

var arr = [ { id: 1,
    name: 'Alex'},
  { id: 2,
    name: 'John'},
  { id: 3,
    name: 'Mary'}
];

var block_ids = [1,2];
var result = _.reject(arr, function (obj) {
    return block_ids.indexOf(obj.id) > -1;
}); 

console.log(result);

DEMO




回答3:


Pure ECMAScript solution:

names.filter(function(element) {
    return blocked_ids.indexOf(element.id) === -1}
);


来源:https://stackoverflow.com/questions/25523657/underscore-js-difference-on-array-and-array-with-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!