How to remove empty elements of an array in JavaScript

Last updated on Jun 1, 2021 by Suraj Sharma



In this tutorial, you will learn to remove empty elements of an array in Javascript using ES6 Array.filter() and Array.forEach() methods.


1. Use Array.filter method


You can use the Array.filter method to filter out all the empty and falsy values of an array


const array = ["", undefined, null, "javascript", NaN, {}];

const nonEmptyArray = array.filter((element)=>{
  return !!element; // or use Boolean(element);
});

console.log(nonEmptyArray); // ["javascript", {}];

// original array remains unaffected.
console.log(array); // ["", undefined, null, "javascript", NaN, {}];

The filter method returns a new array without affecting the array on which it is called.


2. Use Array.forEach method


Another way to remove all the empty and falsy values from an array is to use the forEach() method.

The Array.forEach() method takes a callback function to iterate through all the elements in the array and pushes non empty and truthy values to a new array.


const array = ["", undefined, null, "javascript", NaN, {}, false];

const nonEmptyArray = [];

array.forEach((element)=>{
  if (!!element) {
    nonEmptyArray.push(element);
  }
});

console.log(nonEmptyArray); // ["javascript", {}];


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.