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?
To remove all null values from an array:Use the Array. filter() method to iterate over the array. Check if each element is not equal to null . The filter() method returns a new array containing only the elements that satisfy the condition.
We can use an array instance's filter method to remove empty elements from an array. To remove all the null or undefined elements from an array, we can write: const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ]; const filtered = array. filter((el) => { return el !==
To remove all undefined values from an array:Create an empty array that will store the results. Use the forEach() method to iterate over the array. Check if each element is not equal to undefined . If the condition is met, push the element into the results array.
To check if all of the values in an array are equal to null , use the every() method to iterate over the array and compare each value to null , e.g. arr. every(value => value === null) . The every method will return true if all values in the array are equal to 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With