Remove Empty String Elements from String Array

To remove empty string elements from string array in JavaScript, call filter() method on the given string array, and for each element in the array, return true if the string element has a length greater than zero.

The statement to remove empty string elements from string array arr is

arr = arr.filter((x) => x.length>0)

If we would like to remove any other elements that has only the spaces, or any other white space characters, we can first trim the string element, and then check if the length is greater than zero.

arr = arr.filter((x) => x.trim().length>0)

Example

In the following example, we take a string array in arr, remove the empty string elements from the array, and display the resulting array in pre#output.

index.html

Now, let us take a string array arr with some of the elements having only white space characters. We shall use String.trim() method while filtering the array.

index.html

ADVERTISEMENT

Conclusion

In this JavaScript Tutorial, we learned how to remove empty string elements, or elements with only white space characters, from given string array, with example programs.