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?
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; });
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.
This should do it:
_.filter(myArray, function(o){ return o.weight; });
You can also use underscore's reject function.
var newObjects = _.reject(oldObjects, function(obj) {
return obj.weight === 0;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With