Categories
JavaScript Answers

How to Remove Empty Elements from an Array in JavaScript?

Spread the love

Removing empty elements from a JavaScript array is something that we may have to do sometimes.

In this article, we’ll look at how to remove empty elements from a JavaScript array.

Array.prototype.filter

We can use an array instance’s filter method to remove empty elements from an array.

To remove all the null or undefined elements from an array, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter((el) => {
  return el !== null && typeof el !== 'undefined';
});
console.log(filtered);

The filter method treated array holes as undefined .

So we should see:

[0, 1, 2, "", 3, 3, 4, 4, 5, 6]

as the value of filtered .

If we want to remove all falsy values, we can just pass in the Boolean function to filter .

For instance, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter(Boolean);
console.log(filtered);

Falsy values include null , undefined , 0, empty string, NaN and false .

So they’ll return false if we pass them into the Boolean function.

Therefore, filtered is:

[1, 2, 3, 3, 4, 4, 5, 6]

If we want to return an array with only the numbers left, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter(Number);
console.log(filtered);

Then we get the same result.

Or we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = array.filter(n => n);
console.log(filtered);

And also get the same result since the callback’s return value will be cast to a boolean automatically.

Lodash

Lodash also has a filter method that does the same thing as the native filter method.

For instance, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = _.filter(array, Boolean);
console.log(filtered);

to filter out all the falsy values.

Then filtered is [1, 2, 3, 3, 4, 4, 5, 6] .

It also has a compact method that’s specially made to remove falsy values from an array.

For instance, we can write:

const array = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , , ];
const filtered = _.compact(array);
console.log(filtered);

Then we get the same result.

Conclusion

There’re various ways to remove falsy elements from a JavaScript with native array methods or Lodash.

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 *