This tutorial will explain the methods for removing “undefined” values from a JavaScript array.
Is There Any Method For Removing “undefined” Values From a JavaScript Array?
The following JavaScript predefined methods are used for removing undefined values from an array:
Method 1: Remove/Eliminate “undefined” Values From an Array Using “filter()” Method
To remove undefined values from an array, use the “filter()” method. It outputs a new array containing all elements that satisfy a particular test. It accepts a function as an argument that defines the condition against which each element is tested.
Syntax
Follow the given syntax for using the filter() method:
//condition
})
Example
Create an array that contains numbers with “undefined” values:
Call the filter() method where the callback function returns the elements that are not equal to “undefined”:
return element !== undefined;
});
Finally, display the resultant array on the console:
As you can see, the output which indicates that the undefined values have been successfully removed:
Method 2: Remove/Eliminate “undefined” Values From an Array Using “reduce()” Method
Another way to remove undefined values from an array is to use the JavaScript “reduce()” method. It is used for iterating over an array and accumulating/collecting a single value based on the array’s elements. It accepts a callback function as an argument that is called on every element in the array, and the resultant value is used as the accumulator for the next iteration.
Syntax
The following syntax is utilized for reduce() method:
//condition
}, initialValue)
Example
Invoke the reduce() method with the callback function an initial value that is an empty array ([ ]). The callback function will iterate the array and pick the elements that are not undefined and push them into the accumulator array. After each iteration, the callback function outputs the accumulator array:
const filteredArray = array.reduce((accum, element) => {
if (element !== undefined) {
accum.push(element);
}
return accum;
}, []);
Lastly, display the resultant accumulator array on the console:
Output
We have compiled all the essential information for removing undefined values from an array in JavaScript.
Conclusion
To remove “undefined” values from an array, utilize the JavaScript predefined “filter()” method or the “reduce()” method. Both methods are good for removing undefined values while the filter() method is best because there is no need to push elements in another array. This tutorial explained the ways for removing “undefined” values from an array.