How to remove an empty string from an array in JavaScript

In this tutorial, let’s look at how to remove an empty string from an array in JavaScript.

As you know, an array is a collection of data, and this data can be homogenous (of one data type) or heterogenous (mixed data types).

Let’s assume we have an array of strings, and among those strings, some of them are empty.

Empty strings hold no value, so removing them won’t affect our array in terms of its overall value. So, let’s look at how to do that now.

Using the ‘filter’ method

The easiest way to remove empty strings from an array is by using the ‘filter’ method. This method can be used to filter elements that match a given condition from an array.

It iterates through the array, and for every iteration, the current element’s value will be stored in a temporary variable, which can be later used in our condition to manipulate the result.

This method doesn’t change the value of the original array but returns a new array with the ‘filtered’ values in it.

So, if we give the condition as fruit != ‘’ for every iteration, meaning, if we filter the values that are not an empty string, we’ll get a new array that comprises entirely of non-empty string values.

Now, you can re-assign this new array back to the original variable ‘fruits’, which would effectively remove empty strings from our array, as shown below:

let fruits = ['Grapes', '', 'Apples', 'Oranges', '', 'Banana', ''];
fruits = fruits.filter((fruit => fruit !== ''));
console.log(fruits); //['Grapes', 'Apples', 'Oranges', 'Banana'] 

Using the ‘map’ method

The ‘map’ method works similar to the ‘filter’ method. It iterates through our array, and for every iteration, the current value will be stored in a temporary variable of our choice (‘fruit’ in our case).

But unlike the ‘filter’ method, with ‘map’, you can perform some calculations with the current value.

In our example below, we’re checking if the current value of ‘fruit’ is an empty string. If it isn’t, we’re pushing it to the newFruits array.

Once the map method finishes iterating through the array, the newFruits variable will have the filtered version of the ‘fruits’ array, as shown below:

let fruits = ['Grapes', '', 'Apples', 'Oranges', '', 'Banana', ''];
let newFruits = [];
fruits.map(fruit => {
    if(fruit !== '') {
        newFruits.push(fruit);
    }
});
console.log(newFruits); //['Grapes', 'Apples', 'Oranges', 'Banana'] 

Using the ‘reduce’ method

You can use the ‘reduce’ method instead as well. The ‘reduce’ method, as the name implies, can be used to perform a cumulative operation of all the elements of the array to arrive at a single result. That’s how it’s supposed to be used, but that’s not how we’re going to use it for our case.

Just like the ‘map’ method, for every iteration, you can check if the current value is an empty string and push the non-empty strings.

The main difference between ‘map’ and ‘reduce’ is that we don’t have to create a new array here. It comes with the method because we need a temporary variable that’ll store the cumulative result.

This is how it works:

1. In our example, ‘newFruits’ will store the cumulative result (non-empty values in an array format) and ‘fruit’ will contain the current value of the iteration.

2. We can just push our non-empty values to newFruits if the condition matches in the current iteration.
Finally, return newFruits to replace the array in the ‘fruits’ variable, as shown below:

let fruits = ['Grapes', '', 'Apples', 'Oranges', '', 'Banana', ''];
fruits = fruits.reduce((newFruits,fruit) => {
    if(fruit !== '') {
        newFruits.push(fruit);
    }
    return newFruits;
}, []);
console.log(fruits); //['Grapes', 'Apples', 'Oranges', 'Banana'] 

Using loops and a new array

Instead of using the higher order JavaScript Array methods, you can use the good old ‘for’ and ‘while’ loops to arrive at the same result.

1. As shown below, create a new variable ‘newFruits’ and assign an empty array to it to start with.
2. Then, create a ‘for’ loop (or ‘while’ loop) that iterates through the length of the array.
3. For every iteration, check if fruits[i] (current value) is not an empty string.
4. If it isn’t an empty string, push it into the newFruits array.
5. That’s it!

let fruits = ['Grapes', '', 'Apples', 'Oranges', '', 'Banana', ''];

let newFruits = [];

for(let i = 0; i < fruits.length; i++) {
    if(fruits[i] !== '') {
        newFruits.push(fruits[i]);
    }
}

console.log(newFruits); //['Grapes', 'Apples', 'Oranges', 'Banana'] 

Though the example above was created with a ‘for’ loop, you can instead use ‘while’ and ‘do while’ loops as well.

Using forEach and the splice method

You can also use the ‘forEach’ and ‘splice’ methods together. The ‘forEach’ method iterates through an array as well, but here, for every iteration, you can get the ‘index’ of the current element.

So, instead of just creating a new array and pushing the element into it, why don’t we use the ‘splice’ method to remove the offending values from the original array?

This is how it goes:

1. For this example, you’re going to check if our array item is an empty string now, because if it is, you’re going to remove it using the ‘splice’ method.
2. You can use the index you get for every iteration to splice the array at that index. The ‘splice’ method requires 2 arguments, the first is the position from which you want the array items removed (which is from ‘index’, in our case), and the second argument refers to the number of items you want removed.
3. We can mention the number of items to be removed as 1. This way, the item (value) pertaining to the ‘index’ will be removed, as shown below:

let fruits = ['Grapes', '', 'Apples', 'Oranges', '', 'Banana', ''];

fruits.forEach((fruit,index) => {
    if(fruit === '') {
        fruits.splice(index,1);
    }
});

console.log(fruits); //['Grapes', 'Apples', 'Oranges', 'Banana'] 

You can also use the ‘for’ or ‘while’ loops with the ‘splice’ method to perform the same operation.

Sort the array and pop the empty strings

The ‘sort’ method can be used to sort the array in an ascending order by default. With strings, that means the empty strings will be pushed to the front of the array, since their value is equivalent to 0.

Once done, you can do this:

1. Check if the first value of the array is still an empty string with a ‘while’ loop condition.
2. If it is, use the ‘shift’ method to remove the first item.
3. Continue doing this to remove all the empty elements, so ‘fruits’ will now only have non-empty string values, as shown below:

let fruits = ['Grapes', '', 'Apples', 'Oranges', '', 'Banana', ''];
fruits.sort();
console.log(fruits); // ['', '', '', 'Apples', 'Banana', 'Grapes', 'Oranges']

while(fruits[0] === '') {
    fruits.shift();
}

console.log(fruits); //['Grapes', 'Apples', 'Oranges', 'Banana'] 

That’s it! In this tutorial, we’ve taken a deep look at the various possible ways of removing an empty string from an array in JavaScript.

Leave a Comment