Remove Null Values from an Array in Javascript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

banner

Photo by Becca Tapert

Remove Null Values from an Array #

To remove all null values from an array:

  1. Call the filter() method, passing it a function.
  2. The function should check whether each array 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, containing 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. Create an empty array, that will store the results.
  2. Use the forEach() method to iterate over the array.
  3. On each iteration check if the current 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 pass to the Array.forEach method gets invoked with each element in the array.

We conditionally check if the current element is not equal to null before pushing it into the results array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee