How to Remove Empty Elements from an Array in Javascript

To remove empty elements from a JavaScript Array, the filter() method can be used, which will return a new array with the elements passing the criteria of the callback function.

The filter() method creates an array filled with all array elements that pass a test. To remove null or undefined values do the following:

const array = [0, null, 1, "", 2, undefined, 2, , , , , 4, , 4, , 5, , 6, , , , ];
const arrFiltered = array.filter(el => {
  return el != null && el != '';
});
console.log(arrFiltered);
This function wouldn't remove elements that are an empty string.

To remove falsy elements that include an empty string "", 0, null, NaN, undefined, and false, pass the Boolean constructor function to the filter method, or return the same element in the filter function:

let arrFiltered = array.filter(Boolean);

Here, the filter method invokes the Boolean constructor as a function to convert the value.

Or

let filtered = array.filter(function (el) {
  return el;
});

In this case, the filter method turns the returned value of the callback to Boolean.

If there are holes in the arrays, you can remove them by using the filter method passing a callback that returns true like this:

let array = [0, , , 1, , , , 2, , , , 3],
  cleanArray = array.filter(function () {
    return true
  });
console.log(cleanArray); // [ 0, 1, 2, 3 ]

The filter() Method

The filter() method constructed a new array with all elements passing the test implemented by the provided function. This method invokes a provided callback function once for each element in the array and creates a new array that contains all the values for which callback returns a value is true. Array elements that don't pass the callback test are opt out and aren't included in the new array.

Do you find this helpful?

Related articles