Remove Undefined Values from an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove Undefined Values from an Array #

To remove all undefined values from an array:

  1. Use the Array.filter() method to iterate over the array.
  2. Check if each value is not equal to undefined and return the result.
  3. The filter() method will return a new array that doesn't contain any undefined values.
index.js
const arr = ['a', undefined, 'b', undefined, 'c', undefined]; const results = arr.filter(element => { return element !== undefined; }); console.log(results); // 👉️ ['a', 'b', 'c']

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

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

We explicitly check if each element is not equal to undefined to exclude all undefined values.

The filter method doesn't 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 undefined 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. Check if each element is not equal to undefined.
  4. If the condition is met, push the element into the results array.
index.js
const arr = ['a', undefined, 'b', undefined, 'c', undefined]; const results = []; arr.forEach(element => { if (element !== undefined) { results.push(element); } }); console.log(results); // 👉️ ['a', 'b', 'c']

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

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

The results array does not contain any undefined values.

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.