How to Remove Empty Elements from JavaScript Array

Web developers commonly rely on arrays to store and manipulate data. Often these arrays contain empty elements. An empty element is one which does not have any value, not even undefined or null. Such elements can cause issues in your program, if not handled beforehand. In this article, we will learn how to remove empty elements from JavaScript array.

Why Remove Empty Elements

Empty elements are those array elements that do not contain any value. When we import data from a file or other system, it is common for the data to contain empty values. Sometimes, when you convert another data type such as JSON string to an array, it can also result in empty elements. For example, the array a = [1, , 3] contains an empty element after 1 and before 3. Such elements can cause errors in your JavaScript code. For example, if you are processing every element of the array and your code does not factor empty elements, then it can cause an error and terminate execution. Therefore, it is important to remove empty elements from your JavaScript array.

How to Remove Empty Elements from JavaScript Array

Here are the different ways to remove empty elements from JavaScript array.

1. Using Filter Function

Every JavaScript array supports filter method, that allows you to create a new array from another array, based on elements that satisfy one or more conditions. There are several ways to use filter function to remove empty elements from array.

Let us say you have the following JS array with empty elements.

var a = [1, 2, '', null, 3, undefined, 4];

Here are some of the ways to use filter function to remove empty elements.

You can define a simple function that returns the given element. In this case, it will return only truth values.

let a1 = a.filter(function (e) {
return e;
});

console.log(a1); // output is [1, 2, 3, 4]

You can shorten it using arrow function as shown.

console.log(a.filter(n=>n)); // output is [1, 2, 3, 4]

Alternatively, you can also define a filter function that checks if each element of the array is true or false, that is non empty or empty. It will also return an array of non-empty elements.

console.log(a.filter(Boolean)); // output is [1, 2, 3, 4]

You can also put a condition that checks if the element is a Number or not.

console.log(a.filter(Number)); // output is [1, 2, 3, 4]

2. Using Flat Method

In the above method, the filter function removes not only empty items but also items that are null or undefined. Sometimes, you may want to remove only empty items and retain the rest. In such cases, you can use flat method available for every array. Here is an example to illustrate the difference between this solution and the above one.

var a = [1, 2, , '', null, 3, undefined, 4];
console.log(a.flat()); // output is [ 1, 2, '', null, 3, undefined, 4 ]

The above solution removes only empty items but retains empty strings, numbers and items that are undefined.

3. Using Splice Method

Splice method is used to add/remove one or more items in an array. It can also be used to remove empty items from the array. Here is an example to illustrate it.

var a = [1, 2, , '', null, 3, undefined, 4];
for (let i = a.length - 1; i >= 0; i--) {
if (!a[i]) {
a.splice(i, 1);
}
}
console.log(a); // output is [ 1, 2, 3, 4 ]

In the above code, we iterate through the array in reverse order. In each iteration, we check if the item is empty or not. If the item is empty, then we call splice function to remove the item. You can customize it to remove only specific items in an array.

4. Using Reduce Method

Generally, reduce method is used to reduce an array to a single value but it can also be used to remove empty items from array. Here is its syntax.

array.reduce( function(total, current_value, current_index, array), initial_value )

Here is an example to use reduce method to remove empty items from array.

var a = [1, 2, , '', null, 3, undefined, 4];
var a1 = a.reduce( (acc, e)=> {
if (e) {
acc.push(e);
}
return acc;
}, []);

console.log(a1); // output is [1, 2, 3, 4]

In the above code, we first initiate an empty array. Then we call reduce method on every array item of array a. In each call, we check if item exists or not. If it exists, we push it into array a1.

5. Using Push Method

Push function is used to push an item into a JavaScript array. You can also use it to remove empty items.

var a = [1, 2, , '', null, 3, undefined, 4];
var a1=[];
a.forEach((element) => {
if (element) {
a1.push(element);
}
});
console.log(a1); // output is [ 1, 2, 3, 4 ]

In the above method, we call forEach() method for the array, to loop through the items of array. In each iteration, we first check if the element exists or is empty. If it exists, then we push it into a1 array. This solution will also remove empty strings, nulls and undefined items.

6. Using jQuery

jQuery is a popular third party JavaScript library that contains many useful functions for data and DOM manipulation. It provides grep function that can be used for our purpose. It is similar to filter() function and removes items that do not match a given search criteria. Here is an example to remove empty items from array, using grep function.

var a = [1, 2, , '', null, 3, undefined, 4];
var a1 = a.reduce( (acc, e)=> {
// Check if the current element is truthy
if (e) {
acc.push(e);
}
return acc;
}, []); // Initialize acc as empty array

console.log(a1); // output is [1, 2, 3, 4]

In the above code, we define a reducer function that is called for each array item. In each call, it checks if the item exists or not. If it exists, then the item’s copy is pushed to array a1.

Conclusion

In this article, we have learnt many different ways to easily remove empty items from array. The simplest way to remove empty items is to use filter method. But this method will also remove nulls, undefined and empty strings. If you do not want to remove these items but only empty items, then you can call flat() function available for every array. It will only remove empty items but not affect nulls, empty strings or items with undefined value. If you want to customize the removal

Also read:
How to Detect Invalid Date in JavaScript
How to Find Sum of Array of Numbers in JavaScript
How to Search for Object in Array of Objects in JavaScript

Leave a Reply

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