When working with real-time data, you might get an array that includes null
values inside. You surely want to remove those null values before going further for calculations.
Removing Null Values From the Array with filter
method
The simplest solution to this problem is to use the filter
method on array that contains null values. You can check for the null values with if
conditions inside the callback. Here is a simple example to remove null values from array.
1 2 3 4 5 6 7 8 9 |
const arr = [1, 2, null, 4, null, 6]; const filteredArr = arr.filter(val => val !== null); console.log(filteredArr); // [1, 2, 4, 6] |
Removing Null values From Array with Short Code
You can make the above code simpler by using Boolean
as an argument to filter function. The Boolean
argument will filter all the falsy
values like null
, undefined
, false
from the array. The following is the shortest code to remove false values from array.
1 2 3 4 5 6 7 8 9 |
const arr = [1, 2, null, 4, null, 6]; const filteredArr = arr.filter(Boolean); console.log(filteredArr); // [1, 2, 4, 6] |
You can read more about filter function in JavaScript.
Conclusion
You can remove undefined or falsy values from an array with filter
function in JavaScript. The filter function can take a callback function or just Boolean
to filter all the null or falsy values.