In JavaScript, Arrays can consist of undefined, Null, and NaN values. There are several methods available to remove undefined values from an Array in JavaScript.
Remove undefined values from an Array using the filter() method
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
The function passed to the filter method gets invoked with each array element, and all the truthly values returned by the function will be added to a new Array.
- Call the
Array.filter()
method by passing a function to it - The function is predicate and checks each element in an array is not equal to
undefined
. - The
filter()
method will return the new Array, excluding theundefined
values
const antivirusArr = ['Microsoft Defender', 'Norton Antivirus', undefined, 'BitDefender Antivirus', undefined, undefined];
const results = antivirusArr.filter(element => {
return element !== undefined;
});
console.log(results);
Output
[ 'Microsoft Defender', 'Norton Antivirus', 'BitDefender Antivirus' ]
The filter method will not modify the contents of the original Array. It returns a new Array containing the elements that have satisfied the condition.
Remove undefined values from an Array using the forEach() method
Another approach is to use the forEach()
method to traverse all the elements in an Array and push the elements that are not undefined
to a new Array.
- Create an empty Array that will store the output.
- Using the
forEach()
method, iterate all the elements in an Array. - During each iteration, perform a conditional check if the values are not equal to
undefined
and if the condition is met, push the element to an empty array.
const antivirusArr = ['Microsoft Defender', 'Norton Antivirus', undefined, 'BitDefender Antivirus', undefined, undefined];
const output = []
antivirusArr.forEach(element => {
if (element !== undefined) {
output.push(element);
}
});
console.log(output);
Output
[ 'Microsoft Defender', 'Norton Antivirus', 'BitDefender Antivirus' ]
Note: The function we pass to the forEach()
method will get called while iterating each element of an Array.
Conclusion
We can use Array.prototype.filter()
and Array.prototype.forEach()
methods to remove undefined values from an Array in JavaScript. The main difference between these two methods is forEach()
method loops over an array and executes the callback, but the filter()
method executes the callback and checks its return value.