Categories
JavaScript Answers

How to remove undefined values from array with JavaScript?

Spread the love

Sometimes, we want to remove undefined values from array with JavaScript.

In this article, we’ll look at how to remove undefined values from array with JavaScript.

How to remove undefined values from array with JavaScript?

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.

Conclusion

To remove undefined values from array with JavaScript, we call the filter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *