7

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?

6 Answers 6

24

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; });
Sign up to request clarification or add additional context in comments.

1 Comment

Removing implies identity preservation, this returns a copy so It's actually querying.
3

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.

Comments

3

This should do it:

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

Comments

2

You can also use underscore's reject function.

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

Comments

1

Old question but my 2 cents:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.