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 unders
The best solution is to use compact, but the default behaviour of the filter function when you don't include a specific truth test function is to remove falsy values
For example:
_.filter([null, {name:'John'}, null, {name:'Jane'}])
returns a object array without the nulls:
[{name:'John'}, {name:'Jane'}]
This will work for you
Filter
_.filter(arr,function (value) {
return value!==null;
})
Reject
_.reject(arr,function (value) {
return value===null;
})
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);
Try using _.without(array, *values)
it will remove all the values that you don't need. In your case *values == null
http://underscorejs.org/#without
From underscore documentation
without_.without(array, *values)
Returns a copy of the array with all instances of the values removed.
So just use this method
var a = [null, {name:'John'}, null, {name:'Jane'}]
a = _.without(a, null);