;

How to Remove Empty Elements from an Array in Javascript


Tutorialsrack 27/11/2021 Jquery Javascript

In this article, you’ll learn how to remove empty, null, or undefined elements from an array in javascript. In Javascript, there are various ways to remove empty, null, NaN, or undefined elements from an array.

Here are some examples of empty, null, NaN, or undefined elements from an array in javascript.

Example 1: Using filter() Method

In this example, we used the array filter() method and passed a function to the method which returns the element currently getting looped.

Example 1: Using filter() Method
// array with empty, null, NaN, false or undefined elements
const arr = [1, , , "", 2, 3, 4, 56, "text", null, undefined, 67, , 77, 89, null, NaN, false];

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

console.log(newArr); 
//Output => [1, 2, 3, 4, 56, "text", 67, 77, 89]

Example 2: Using for Loop

In this example, we used the for loop and check if the element exists and if it exists push to the new array:

Example 2: Using for Loop
// array with empty, null, NaN, false or undefined elements
const arr = [1, , , "", 2, 3, 4, 56, "text", null, undefined, 67, , 77, 89, null, NaN, false];

// 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); 
//Output => [1, 2, 3, 4, 56, "text", 67, 77, 89]

Example 3: Using Array.forEach Method

In this example, we used the Array.forEach() Method. This 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.

Example 3: Using Array.forEach Method
// array with empty, null or undefined elements
const arr = [1, , , "", 2, 3, 4, 56, "text", null, undefined, 67, , 77, 89, null, NaN, false];

// 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
arr.forEach((element)=>{
  if (!!element) {
    newArr.push(element);
  }
});

console.log(newArr); 
//Output => [1, 2, 3, 4, 56, "text", 67, 77, 89]

I hope this article will help you to understand how to remove empty elements from an array in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags