To remove undefined values from array with JavaScript, we call the filter
method.
For instance, we write
const data = [42, 21, undefined, 50, 40, undefined, 9];
const newData = data.filter((element) => {
return element !== undefined;
});
to call data.filter
with a callback that checks if each element
in data
isn’t undefined
.
Then items that aren’t undefined
are returned in a new array.