Remove Null Values from an Array in Javascript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove Null Values from an Array #

To remove all null values from an array:

  1. Use the Array.filter() method to iterate over the array.
  2. Check if each element is not equal to null.
  3. The filter() method returns a new array containing only the elements that satisfy the condition.
index.js
const arr = ['one', null, 'two', null, 'three', null]; const results = arr.filter(element => { return element !== null; }); console.log(results); // 👉️ ['one', 'two', 'three']

The function we passed to the Array.filter method gets called with each element in the array.

If the function returns a truthy value, the element gets added to the results array.

We explicitly check if each element is not equal to null to only add non-null elements to the new array.

The filter method does not change the contents of the original array. It returns a new array that contains only the elements that satisfy the condition.

An alternative approach is to use the forEach method.

To remove all null values from an array:

  1. Declare a results variable and set it to an empty array.
  2. Use the forEach() method to iterate over the array.
  3. Check if each element is not equal to null.
  4. If the condition is satisfied, push the element into the results array.
index.js
const arr = ['one', null, 'two', null, 'three', null]; const results = []; arr.forEach(element => { if (element !== null) { results.push(element); } }); console.log(results); // 👉️ ['one', 'two', 'three']

The function we passed to the Array.forEach method gets invoked with each element in the array.

On each iteration, we check if the current element is not equal to null before pushing it into the results array.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.