How To Remove Empty Elements From An Array In JavaScript

Remove empty elements from an array in javascript

Being able to remove empty elements from an array in JavaScript is an essential skill that we all should know while working with JavaScript arrays. There are many different ways, but in this tutorial, we will show you the two most common methods to do it.

Remove empty elements from an array in JavaScript

Method 1: Using a for loop

Calling a for loop is always a go-to method when we want to scan through every element of our array. And I will show you how we can use that to remove empty elements. Our idea is: we will look at each of our elements and check if it is empty, null, or undefined. If not, then we will push that element to our result.

We use the array.push method to push the passed element to our new array. 

Syntax

array.push(element1, element2,...)

Parameters:
element1, element2,…: the elements/items to add to the end of the array. 

Now let’s describe our idea in JavaScript:

var myArr = [34, 2323, 329, , , ,84, 328, null, undefined, ,56, 97];
var result = [];

for (let i=0; i<myArr.length; i++) {
  if (myArr[i]) {
    result.push(myArr[i]);
  } else continue;
}

console.log(result);

Output: 

[34, 2323, 329, 84, 328, 56, 97]

Method 2: Using array.filter()

The array.filter() method will create a new array that contains only the elements of the old array that pass the test provided by a function. 

Syntax:

array.filter(function(currentValue, index, arr), thisValue)
  • function(): a function or condition that you want to run through every element.
  • currentValue: the current element’s value.
  • index: the current element’s index. 
  • arr: the current element’s array.
  • thisValue: A value passed to the function as its this value.

Let’s apply it to remove the empty elements: 

var myArr = [34, 2323, 329, , , ,84, 328, null, undefined, ,56, 97];
var result = [];

function check(element) {
  return element !== '' && element !== null && element !== undefined;
};

result = myArr.filter(check);
console.log(result);

Output: 

[34, 2323, 329, 84, 328, 56, 97]

Summary 

We have guided you through two different ways to remove empty elements from an array in JavaScript. The ideas are very simple: using a for loop and array.filter(). 

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *