Join my Vue.js course while it's free 👀

Remove empty strings from a JavaScript Array

April 24, 2022  ‐ 2 min read

The most convenient method I found to remove empty strings from an array in JavaScript is by using the filter method for arrays.

["a", "b", "", "c"].filter((letter) => letter);
// => ['a', 'b', 'c']

The filter() method creates a new Array instance containing the values that evaluate as true in the callback function that is passed as an argument. Thus all values that are falsy, like false and null for example, would be filtered out array above as well.

More explicitly you can filter out empty strings by checking whether a value is not equal to an empty string, this makes sure that you remove only empty strings from the array:

["a", "b", "", "c"].filter((letter) => letter !== "");
// => ['a', 'b', 'c']

As I briefly mentioned above, the filter() method creates a new Array instance, so it doesn't make changes in-place. Which means that if you access your array as a variable you might want to reassign its value. Otherwise the initial array would be still intact.

let letters = ["a", "b", "", "c"];

letters.filter((letter) => letter !== "");

// The value of 'letters' isn't changed
console.log(letters); // ['a', 'b', '', 'c']

// Instead you should assign the result to 'letters'
// or a different variable.
letters = letters.filter((letter) => letter !== "");
console.log(letters); // ['a', 'b', 'c']