Remove Empty Strings from an Array in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

Remove Empty Strings from an Array #

To remove all empty strings from an array:

  1. Call the filter() method, passing it a function.
  2. On each iteration of the function, check if the current element is not equal to an empty string.
  3. The filter method returns a new array containing only the elements that satisfy the condition.
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 invoked with each element in the array.

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

We check if each element is not equal to an empty string and only include those to the results array.

The filter method does not 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. Create an empty array, that will store the results.
  2. Use the forEach() method to iterate over the array.
  3. On each iteration check if the current 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 pass to the Array.forEach method gets called with each element in the array.

We conditionally check if the current element is not equal to an empty string before pushing it into the array.

The final array does not contain empty string elements.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee