JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to remove empty elements from an array in JavaScript?

To remove empty elements from an array, you must follow the following steps:

  1. Call the filter() method on the array from which you want to remove empty elements.
  2. Inside the callback function of the filter() method, check if an array element is not equal to null, undefined, "" (empty string), and NaN.
  3. If the array element satisfies the condition, then return true and that element becomes a part of the new array.
let shoppingList = ['Apples', 'Milk', null, 'Bread', undefined, "Biscuits", NaN, ""];

let result = shoppingList.filter(element => {
  if(element !== null && element !== undefined && !Number.isNaN(element) && element !== ""){
    return true;
  }
});

console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]

The callback function of the filter() method is called for each array element. You specify the condition using the logical && operator inside the callback function so that you can remove empty elements from the array.

Note: The filter() method does not modify the original array. Instead, it returns a new array whose elements satisfy the condition.

There is an alternative way if you don't want to use the filter() method, which is to use the forEach() method.

To remove empty elements from an array using the forEach() method, you must follow the following steps:

  1. First, create an empty array that will hold array elements that are not empty elements.
  2. Call forEach() method on the array from which you want to remove null values.
  3. Inside the forEach() method, check if the current processing element is not equal to null, undefined, empty string and NaN. If the condition is satisfied, push that array element into the empty array created in step 1.
let result = [];
let shoppingList = ['Apples', 'Milk', null, 'Bread', undefined, "Biscuits", NaN, ""];

shoppingList.forEach(element => {
  if(element !== null && element !== undefined && !Number.isNaN(element) && element !== ""){
    result.push(element);
  }
});

console.log(result); //["Apples", "Milk", "Bread", "Biscuits"]

Recommended Posts