user3432681 user3432681 - 7 months ago 12
Javascript Question

How to delete a object in a list? Javascript nodejs and underscore

Hello I am new to Javascript and NodeJS, but I need to delete a object in a array with a boolean in the list. There are 3 friends in the list and 2 friends with

isEvil = true;
So i need to delete 2 friends and the output must be 1.
This is what i tried.

MyTry 1:

_.each(user.friends, function(friend) {
if(friend.isEvil){
delete friend;
}
});
console.log(user.friends.length); //output is 3


If I do this it will delete all the properties but there is still a empty object there: MyTry 2:

_.each(user.friends, function(friend) {
if(friend.isEvil){
delete f.property1;
delete f.property2;
}
});
console.log(user.friends.length); //output is 3


And the last one i tried is:

_.each(user.friends, function(friend, key) {
if(friend.isEvil){
delete user.friends[key];
}
});
console.log(user.friends.length); //output is 3

Answer

just use the _.filter(list, predicate, [context]) function provided with underscore:

_.filter(user.friends, function(friend){ 
                             return !friend.isEvil; 
  });

for more info: http://underscorejs.org/#filter

Comments