To remove empty strings from an array in JavaScript, you can use the Array.filter()
method.
The Array.filter()
method takes a callback function as an argument. The JavaScript compiler one by one passes each element of the array to the callback function as a parameter.
Inside the callback function, you can then check if the current string which is implicitly passed to the callback function as a parameter is empty or not. If it is empty, return true, otherwise, return false.
This will finally return a new array that will contain only those strings which are not empty.
For example:
// Array with empty strings const fruits = ['apple', '', '', 'mango', 'orange', '']; // Filter non-empty strings const nonEmptyFruits = fruits.filter((str) => str != ""); // Print the new array console.log(nonEmptyFruits);
Output:
[ 'apple', 'mango', 'orange' ]
You can also use the Array.length
property inside the callback function to check if the current string is empty or not.
If the length of the current string is 0, this means the string is empty otherwise not.
// Array with empty strings const fruits = ['apple', '', '', 'mango', 'orange', '']; // Filter non-empty strings const nonEmptyFruits = fruits.filter((str) => str.length>0); console.log(nonEmptyFruits); // Output: 👉 [ 'apple', 'mango', 'orange' ]
Please note that the Array.filter()
method doesn’t modify the original array. It instead returns a new array containing the filtered elements.
Remove Empty Strings from Array using a For…of Loop
You can also use a for...of
loop to remove all the empty strings from an array.
In this method, you have to manually run a for loop over the given array and then one by one check if the string is empty or not.
If the current string is non-empty, push it into a new array using the Array.push()
method.
// Array with empty strings const fruits = ['apple', '', '', 'mango', 'orange', '']; // Create an empty array to store non-empty strings const nonEmptyFruits = []; // Run a for loop over the original array for(let str of fruits){ // Check if the current string is non empty if(str!=''){ // Push the string into new array nonEmptyFruits.push(str); } } // Print the new array console.log(nonEmptyFruits);
Output:
[ 'apple', 'mango', 'orange' ]
You can use either of the two approaches to remove the empty strings from an Array. The first approach is pretty straightforward. You don’t have to write much stuff.
On the other hand, the second approach gives you clarity about the steps involved in getting the desired result. This is quite helpful if you are a beginner.
That’s all for the day. Happy Coding.