user1452494
user1452494

Reputation: 1185

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?

Upvotes: 7

Views: 19509

Answers (6)

Alex Dev
Alex Dev

Reputation: 33

return this.data = _.without(this.data, obj);

Upvotes: 0

Nadeem
Nadeem

Reputation: 449

Old question but my 2 cents:

_.omit(data, _.where(data, {'weight':0}));

Upvotes: 1

alengel
alengel

Reputation: 4958

You can also use underscore's reject function.

var newObjects = _.reject(oldObjects, function(obj) { 
    return obj.weight === 0; 
});

Upvotes: 2

codebox
codebox

Reputation: 20254

This should do it:

_.filter(myArray, function(o){ return o.weight; });

Upvotes: 3

p.s.w.g
p.s.w.g

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

Luke
Luke

Reputation: 8407

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.

Upvotes: 3

Related Questions