简体   繁体   中英

Underscore JS difference on array and array with objects

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?

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

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

For example:

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

See this JSFiddle .

Pure ECMAScript solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM