Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Underscore.js to remove object from array based on property

I have an array of objects in javascript. Each object is of the form

obj {
    location: "left", // some string
    weight: 0 // can be zero or non zero
}

I want to return a filtered copy of the array where the objects with a weight property of zero are removed

What is the clean way to do this with underscore?

like image 745
user1452494 Avatar asked May 28 '14 14:05

user1452494


4 Answers

You don't even really need underscore for this, since there's the filter method as of ECMAScript 5:

var newArr = oldArr.filter(function(o) { return o.weight !== 0; });

But if you want to use underscore (e.g. to support older browsers that do not support ECMAScript 5), you can use its filter method:

var newArr = _.filter(oldArr, function(o) { return o.weight !== 0; });
like image 51
p.s.w.g Avatar answered Oct 21 '22 10:10

p.s.w.g


filter should do the job

_.filter(data, function(item) { return !!item.weight; });

the !! is used to cast the item.weight into a boolean value, where NULL, false or 0 will make it false, and filter it out.

like image 20
Luke Avatar answered Oct 21 '22 11:10

Luke


This should do it:

_.filter(myArray, function(o){ return o.weight; });
like image 3
codebox Avatar answered Oct 21 '22 11:10

codebox


You can also use underscore's reject function.

var newObjects = _.reject(oldObjects, function(obj) { 
    return obj.weight === 0; 
});
like image 2
alengel Avatar answered Oct 21 '22 12:10

alengel