0

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?

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

complete and clear answer. Thanks, works like a charm!
0

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 Comments

Well I posted it first so... :) Anyway, glad it works. You could also consider @illfang's for a non-underscore solution.
Ok you're right ;) Answers are almost identical and you were first, so I accepted your answer as the solution :P
0

Pure ECMAScript solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.