How to Remove Empty Strings from an Array in JavaScript
Do you know how to remove empty strings from an array in JavaScript? Sometimes, arrays can have empty strings, and they can cause problems when we work with them.
But don't worry, we've got you covered! In this article, we'll show you how you can remove those empty strings from your arrays using different techniques in JavaScript.
We'll also explore some related concepts, like how to check if a string is empty and how to use the filter() method to manipulate arrays.
Using the Array.filter() method.#
One way to remove empty strings from an array in JavaScript is by using the Array.filter() method.
This method creates a new array with all elements that pass a certain condition. In this case, we can use it to filter out the empty strings.
In the above example, we have an array array that contains some empty strings. We use the filter() method to create a new array filteredArray that only includes elements that are not empty strings.
The callback function element => element !== "" checks if the element is not an empty string.
Remove Empty Strings from Array using a For...of Loop#
Another way to remove empty strings from an array is by using a for...of loop. This loop allows us to iterate over each element in the array and manually check if it is an empty string. If it is not, we add it to a new array.
Here's an example of how to remove empty strings from an array using a for...of loop:
In the above example, we declare an empty array filteredArray to store the non-empty strings.
The for...of loop iterates over each element in the array, and the if statement checks if the element is not an empty string. If it passes the condition, we push it into the filteredArray.
Both the Array.filter() method and the for...of loop provide ways to remove empty strings from an array in JavaScript. Choose the method that best fits your coding style and requirements.