Categories
JavaScript Answers

How to remove empty elements from an array in JavaScript?

Spread the love

To remove empty elements from an array in JavaScript, we call the filter method.

For instance, we write

const arr = [1, 2, , 3, , -3, null, , 0, , undefined, 4, , 4, , 5, , 6, , , ,];
const filtered = arr.filter(Boolean);

to call arr.filter with Boolean to return an array with all the falsy values removed.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.