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
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = ['apple', '', '', 'banana', '', 'mango'];
arr = arr.filter((x) => x.length>0);
for(index = 0; index < arr.length; index++) {
document.getElementById('output').innerHTML += index + ' - ' + arr[index] + '\n';
}
</script>
</body>
</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
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var arr = ['apple', ' ', '\t\n', 'banana', '', 'mango'];
arr = arr.filter((x) => x.trim().length>0);
for(index = 0; index < arr.length; index++) {
document.getElementById('output').innerHTML += index + ' - ' + arr[index] + '\n';
}
</script>
</body>
</html>
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.