How to Remove null Values From a JavaScript Array?

Filtering out all null values from a JavaScript array

To remove only null values from a JavaScript array, you can do the following:

Using Array.prototype.filter()

When the provided callback function to Array.prototype.filter() returns true, the value from the original array is added to the resulting array, or ignored otherwise. Therefore, to add only non-null values to the resulting array you can implement a test in the callback function for the current value to not be null, for example, like so:

// ES5+
const arr = [null, 'foo', '', 0, null, 'bar'];
const newArr = arr.filter((item) => item !== null);

console.log(newArr); // ['foo', '', 0', 'bar']

Using a Loop

You can simply iterate over an existing array and only add all non-null values to a new array, for example, like so:

const arr = [null, 'foo', '', 0, null, 'bar'];
const newArr = [];

for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== null) {
        newArr.push(arr[i]);
    }
}

console.log(newArr); // ['foo', '', 0', 'bar']

You could also shorten this by using logical AND operator (&&) with the condition to check for null values on the left and the operation to add to the new array on the right. In this way, the value would only get added to the new array if the left side of the logical AND operator returns true:

const arr = [null, 'foo', '', 0, null, 'bar'];
const newArr = [];

for (let i = 0; i < arr.length; i++) {
    arr[i] !== null && newArr.push(arr[i]);
}

console.log(newArr); // ['foo', '', 0', 'bar']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.