Skip to main content

How to Remove Empty Strings from an Array In JavaScript

how-to-remove-empty-strings-from-array-in-javascript

How to Remove Empty Strings from an Array In JavaScript

When working with arrays in JavaScript, it's common to encounter scenarios where you need to remove empty strings from an array. Empty strings can clutter the array and affect the desired functionality of your code. Fortunately, JavaScript offers several methods to efficiently remove empty strings from an array. Yyou can effectively filter out the empty strings and obtain a new array containing only the non-empty string values. These methods provide flexibility and allow you to customize the filtering process based on your specific requirements.

In this article, we will explore different approaches to removing empty strings from an array in JavaScript, equipping you with the knowledge to streamline your array manipulation tasks and optimize your code.


01. Using "Array.filter()":

var array = ["Apple", "", "Banana", "", "Cherry", ""];
var filteredArray = array.filter(function (value) {
   return value !== "";
});
console.log(filteredArray);

Output:

["Apple", "Banana", "Cherry"]

In this method, Array.filter() is used to create a new array containing only the non-empty strings. The callback function checks each element and returns true if it is not an empty string.



02. Using "Array.reduce()"

var array = ["Apple", "", "Banana", "", "Cherry", ""];
var filteredArray = array.reduce(function (result, value) {
   if (value !== "") {
      result.push(value);
   }
   return result;
}, []);
console.log(filteredArray);

Output:

["Apple", "Banana", "Cherry"]

Here, Array.reduce() is employed to iterate over the array and build a new array excluding the empty strings. The callback function checks each element and adds it to the result array only if it is not an empty string.



03. Using "for loop"

var array = ["Apple", "", "Banana", "", "Cherry", ""];
var filteredArray = [];
for (var i = 0; i < array.length; i++) {
   if (array[i] !== "") {
      filteredArray.push(array[i]);
   }
}
console.log(filteredArray);

Output:

["Apple", "Banana", "Cherry"]

In this method, a for loop is used to iterate over the array. Empty strings are skipped, and non-empty strings are added to the filteredArray using the push() method.


04. Using "Array.from()" and "Array.filter()"

var array = ["Apple", "", "Banana", "", "Cherry", ""];
var filteredArray = Array.from(array).filter(function (value) {
   return value !== "";
});
console.log(filteredArray);

Output:

["Apple", "Banana", "Cherry"]

Here, Array.from() is utilized to convert the array-like object into a new array. Then, Array.filter() is used to create a new array excluding the empty strings.


Comments