Remove Empty Strings from an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 29, 2022

banner

Photo from Unsplash

Remove Empty Strings from an Array #

To remove all empty strings from an array:

  1. Use the Array.filter() method to iterate over the array.
  2. Check if each element is not equal to an empty string.
  3. The filter method will return a new array that doesn't contain any empty strings.
index.js
const arr = ['a', '', '', 'b', '', 'c']; const results = arr.filter(element => { return element !== ''; }); console.log(results); // 👉️ ['a', 'b', 'c']

The function we passed to the Array.filter method gets called with each element in the array.

If the function returns a truthy value, the filter method adds the element to the results array.

On each iteration, we check if each element is not equal to an empty string and return the result.

The filter method doesn't change the contents of the original array. It returns a new array, containing only the elements that satisfy the condition.

An alternative approach is to use the forEach() method.

To remove all empty strings from an array:

  1. Declare a new variable that stores an empty array.
  2. Use the Array.forEach() method to iterate over the array.
  3. Check if each element is not equal to an empty string.
  4. If the condition is met, push the element into the results array.
index.js
const arr = ['a', '', '', 'b', '', 'c']; const results = []; arr.forEach(element => { if (element !== '') { results.push(element); } }); console.log(results); // 👉️ ['a', 'b', 'c']

The function we passed to the Array.forEach method gets called with each element in the array.

On each iteration, we check if the current element is not equal to an empty string before pushing it into the results array.

The results array doesn't contain empty string elements.

Which approach you pick is a matter of personal preference. I'd go with the filter method as I find it a bit more direct.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.