Remove Undefined Values from an Array in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

banner

Photo by Sean Kong

Remove Undefined Values from an Array #

To remove all undefined values from an array:

  1. Call the filter() method, passing it a function.
  2. The function should check whether each element is not equal to undefined.
  3. The filter method returns a new array, containing only the elements that satisfy the condition.
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 array element.

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 only include defined values in the results 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 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. On each iteration check if the current 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 pass 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 array.

The results array does not contain any elements with value undefined.

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