Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out an array with null values, underscore

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?

like image 861
Joe Avatar asked Aug 22 '14 08:08

Joe


People also ask

How do you filter null values in an array?

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.

How do you remove empty elements from an array?

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 !==

How do you remove an undefined element from an array?

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.

How do you check if an array contains null value?

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 .


2 Answers

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); 
like image 154
Gruff Bunny Avatar answered Sep 17 '22 15:09

Gruff Bunny


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

like image 21
onetwo12 Avatar answered Sep 18 '22 15:09

onetwo12