Reputation: 1185
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?
Upvotes: 7
Views: 19509
Reputation: 449
Old question but my 2 cents:
_.omit(data, _.where(data, {'weight':0}));
Upvotes: 1
Reputation: 4958
You can also use underscore's reject function.
var newObjects = _.reject(oldObjects, function(obj) {
return obj.weight === 0;
});
Upvotes: 2
Reputation: 20254
This should do it:
_.filter(myArray, function(o){ return o.weight; });
Upvotes: 3
Reputation: 149000
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; });
Upvotes: 24