Friday, May 17, 2024
46
rated 0 times [  47] [ 1]  / answers: 1 / hits: 38817  / 10 Years ago, fri, august 22, 2014, 12:00:00

I have this array:



[null, {name:'John'}, null, {name:'Jane'}]


I want to remove the null values. Is there an easy way to do this with underscore?


More From » underscore.js

 Answers
18

If the array contains either nulls or objects then you could use compact:



var everythingButTheNulls = _.compact(list);


NB compact removes all falsy values so if the array could contain zeros, false etc then they would also be removed.



Could also use reject with the isNull predicate:



var everythingButTheNulls = _.reject(array, _.isNull);

[#69690] Wednesday, August 20, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quentinaveryb

Total Points: 102
Total Questions: 100
Total Answers: 93

Location: Colombia
Member since Mon, May 2, 2022
2 Years ago
quentinaveryb questions
Thu, Aug 6, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;