Remove Null Values from Array in Javascript
By Henri Parviainen
Remove empty values from array using filter method
We can filter all null values out from an array by using the built-in Array.prototype.filter method. The following code example also removes all empty strings
, 0
, false
and undefined
values in arrays.
const array = [1, 2, 3, null, " ", , undefined, 4, "Text", 0, false, true];
const removeEmptyValues = array => {
const filtered = array.filter(e => e);
return filtered;
};
// returns [ 1 , 2 , 3 , 4 , 'Text' , true ]
Remove empty elements by using array filter method with boolean expression
Another really simple way to remove all empty values from a javascript array is to combine the filter method with a boolean check expression. This method will also filter out false
, 0
, empty strings
, and undefined
elements.
const removeEmptyValues = array => {
const filtered = array.filter(Boolean);
return filtered;
};
// returns [ 1 , 2 , 3 , 4 , 'Text' , true ]