Borislav Hadzhiev
Wed Oct 13 2021·2 min read
Photo by Sean Kong
To remove all undefined values from an array:
filter()
method, passing it a function.undefined
.filter
method returns a new array, containing only the elements that
satisfy the condition.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.
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:
forEach()
method to iterate over the array.undefined
.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.
undefined
before pushing it into the array.The results array does not contain any elements with value undefined
.