How to remove empty elements from an array in JavaScript?

Published November 27, 2020

To remove empty, null, or undefined elements from an array, we can use the filter() array method and pass a function to the method which returns the element currently getting looped.

This method works because when an empty, null or undefined item is looped, it evaluates to boolean false which will then be filtered out from the array.

Consider this array with some empty elements,

// array with empty elements
const arr = [1, , , , 2, 3, 4, 56, "text", null, undefined, 67, ,];

Our goal is to remove the empty elements and also the null and undefined values from the array.

So let's use the filter() array method and pass a function which returns the item itself like this,

// array with empty elements
const arr = [1, , , , 2, 3, 4, 56, "text", null, undefined, 67, ,];

// use filter() array method
// and return the element which is being looped
const newArr = arr.filter((a) => a);

console.log(newArr); // [1, 2, 3, 4, 56, "text", 67] ✅

Yay! 😃 We got our new array with all the empty, null, undefined values removed from the array.

See this example live in JSBin.

Alternate method: Iterating using a for loop

Another way is to use a for loop and check if the element evaluates to true inside the loop and if it does add that element to the new array this,

// array with empty elements
const arr = [1, , , , 2, 3, 4, 56, "text", null, undefined, 67, ,];

// make a new array
// to hold non-empty values
const newArr = [];

// use for loop
// check if element exists
// and if it exists push to the
// new array
for (let i = 0; i < arr.length; i++) {
  if (arr[i]) {
    newArr.push(arr[i]);
  }
}

console.log(newArr); // [1, 2, 3, 4, 56, "text", 67] ✅

See this example live in JSBin.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter