To remove undefined values from an array in JavaScript, you can use any of these methods –
- Use the Array.filter() method to filter all the values from the array that are not undefined. The Array.filter() method returns a new array that doesn’t contain undefined values.
- Use the Array.forEach() method to iterate over the array, and when there is a value that is not undefined, push it to a new array.
Let’s discuss these methods in detail below.
Array.filter() To Remove Undefined Values From An Array In JavaScript
The Array.filter() method is used to create a new array from an existing array. The new array contains only those elements from the original array for which the callback function returns a truthy value.
Here is how to use this method to remove undefined values from an array –
var arr = ['a', undefined, 'b', null, 'c', NaN];
// remove undefined elements from arr
var newArr = arr.filter(function(value){
return value !== undefined;
});
console.log(newArr);
// ['a', 'b', null, 'c', NaN]
As you can see from the above code, we have created an array with some elements that have a value of undefined.
To remove these values, we have used the Array.filter() method. The callback function passed as an argument to this method returns a truthy value only when the element is not undefined.
All the other elements are filtered out, and a new array is returned that doesn’t contain any undefined values.
Array.forEach() To Remove Undefined Values From An Array In JavaScript
This method can be used to iterate over an array, and for each element in the array, we can check if it is not undefined. If it’s not undefined, then we can push the element to a new array.
Here is how you can use this approach –
var arr = ['a', undefined, 'b', null, 'c', NaN];
// remove undefined elements from arr
var newArr = [];
arr.forEach(function(value){
if(value !== undefined) {
newArr.push(value);
}
});
console.log(newArr); // ['a', 'b', null, 'c', NaN]
As you can see from the code above, we have first created an empty array – newArr.
Then we have used the Array.forEach() method to iterate over our original array – arr.
For each element in the array, it checks if it’s value is not undefined. If the condition evaluates to true, then the element is pushed to the new array.
In this way, all the undefined values are removed from the original array and a new array is returned that doesn’t contain any undefined values.
Final Thoughts
In this article, you learned how to remove undefined values from an array in JavaScript. You can use any of the methods discussed above to achieve this.
If you have any questions, please leave a comment below, and I’ll do my best to answer it.