Working with real data in a project, you might face problems when you have an array that contains empty strings. You might want to remove all the empty strings before displaying data or iterating the array with map
function.
How to Remove Empty String From an Array
The simplest and easiest way to remove all the empty values in an array is to use the filter()
method. You can specify the condition that will not return the empty values. The following example is using the filter
function and removes all the empty strings.
1 2 3 4 5 6 7 |
const cities = ["New York", "Islamabad", "Sydney", "Prague", "", "", "Mumbai"]; console.log(cities.filter((city)=>city!=="")); // output : ["New York", "Islamabad", "Sydney", "Prague", "Mumbai"]; |
Shorthand Syntax to Remove Empty Strings From Array
This filter method can be converted to even more simple syntax by just adding Boolean
as a parameter. Check the following code that uses shorthand syntax to remove empty values.
1 2 3 4 5 6 7 |
const cities = ["New York", "Islamabad", "Sydney", "Prague", "", "", "Mumbai"]; console.log(cities.filter(Boolean)); // output : ["New York", "Islamabad", "Sydney", "Prague", "Mumbai"]; |
You can also read how to remove undefined values from the array when working .map
function.
Conclusion
You can remove all the empty strings from an array with filter
function. The function will return all the truthy values by eliminating all the falsy values. Check the official documentation about filter function in JavaScript.