Sunday, May 12, 2024
167
rated 0 times [  169] [ 2]  / answers: 1 / hits: 19217  / 10 Years ago, wed, may 28, 2014, 12:00:00

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?


More From » underscore.js

 Answers
7

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; });

[#70820] Monday, May 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leandraannabellar

Total Points: 255
Total Questions: 89
Total Answers: 89

Location: England
Member since Sun, May 21, 2023
1 Year ago
;