How To Remove Empty Strings From An Array In JavaScript

remove empty strings from an array in JavaScript
remove empty string from array js

To remove empty strings from an array in JavaScript, you can use any of the following methods –

  1. You can use the Array.filter() method to filter all the strings in the array that are not empty.
  2. You can use the Array.forEach() method to return a new array that contains strings that are not empty.
  3. Use for loop to remove all the non-empty strings.
  4. Use reduce method to accumulate all the non-empty strings from the array.

Let’s discuss each of these methods in detail below.

Remove Empty Strings From An Array In JavaScript

In JavaScript, there are several methods to remove empty strings from an array. Empty strings can sometimes clutter an array and make it difficult to work with or perform specific operations. Therefore, it becomes necessary to filter out these empty strings and obtain a new array that contains only the non-empty string elements.

In this article, we will explore different techniques for removing empty strings from an array in JavaScript. We will examine various approaches using built-in array methods such as filter(), reduce(), forEach(), and also a combination of join() and split() methods.

By understanding these methods, you will be equipped with the knowledge to efficiently clean up arrays by eliminating empty strings. Let’s dive into the different ways you can accomplish this task using JavaScript.

Use Array.filter() To Remove Empty Strings From An Array In JavaScript

The Array.filter() method creates a new array with all the elements that pass the test implemented by the callback function.

In this case, we can use the Array.filter() method to remove all empty strings from an array like this –

var arr = ["", "Hello", "World", ""];

var newArr = arr.filter(function(str) {

  return str !== "";

});

console.log(newArr); // ["Hello", "World"]

In the above code, we have created an array with some empty strings. We have then used the Array.filter() method to filter all the strings in the array that are not empty.

Use Array.forEach() To Remove Empty Strings From An Array In JavaScript

The Array.forEach() method calls a function for each element in the array. In this case, we can use the Array.forEach() method to return a new array that contains strings that are not empty.

var arr = ["", "Hello", "World", ""];

var newArr = [];

arr.forEach(function(str) {

  if(str !== "") {

    newArr.push(str);

  }

});

console.log(newArr); // ["Hello", "World"]

In the above code, we have created an array with some empty strings. We have then used the Array.forEach() method to push all those elements to a new array that are not empty.

This way, when the forEach() loop terminates, you have a new array with non-empty strings.

Use A for Loop

To remove empty strings from a JavaScript array using a for loop, you can follow the steps below:

  • Create an array that contains both empty and non-empty strings:
const array = ["Hello", "", "World", "", "OpenAI", ""];
  • Initialize a new empty array that will store the non-empty strings:
const newArray = [];
  • Use a for loop to iterate over each element in the original array:
for (let i = 0; i < array.length; i++) {
  // Inside the loop, access each element using the index (i):
  const element = array[i];

  // Check if the element is not an empty string:
  if (element !== "") {
    // If the element is not empty, add it to the new array:
    newArray.push(element);
  }
}
  • After the loop completes, the newArray will contain only the non-empty strings. You can then use it as needed:
console.log(newArray);

By iterating over each element of the original array using the for loop, we can selectively add non-empty strings to a new array, effectively removing the empty strings. This approach provides granular control and is especially useful in older JavaScript versions or situations where you need to perform additional logic during the removal process.

Remember to adapt the variable names (array and newArray) as per your specific use case.

Use reduce() Method

Here’s how you can use the reduce() method to remove empty strings from a JavaScript array:

  • Create an array that contains both empty and non-empty strings:
const array = ["Hello", "", "World", "", "OpenAI", ""];
  • Use the reduce() method on the array, passing in a callback function and an initial value:
const newArray = array.reduce((accumulator, element) => {
  // Inside the callback function, check if the element is not an empty string:
  if (element !== "") {
    // If the element is not empty, add it to the accumulator (newArray):
    accumulator.push(element);
  }
  // Return the accumulator for the next iteration:
  return accumulator;
}, []);
  • After the reduce() method completes, the newArray will contain only the non-empty strings. You can then use it as needed:
console.log(newArray);

In this approach, the reduce() method applies the callback function to each element of the array. If the element is not an empty string, it is added to the accumulator (the newArray). The reduce() method iterates through all the elements of the array, continually updating the accumulator. Finally, the resulting newArray contains only the non-empty strings.

Using reduce() provides a concise and functional approach to remove empty strings from an array in JavaScript. Remember to adjust variable names (array, newArray, and accumulator) based on your specific requirements.

Conclusion

In JavaScript, removing empty strings from an array is a common task when dealing with data processing or manipulation. Throughout this discussion, we explored different approaches to achieve this goal.

We learned that using methods such as filter() with a conditional statement, utilizing a for loop, or employing the reduce() method allows us to selectively remove empty strings from an array. These techniques provide flexibility and control over the removal process, catering to various programming preferences and requirements.

With these techniques in hand, you can confidently handle arrays containing empty strings, ensuring cleaner and more streamlined data structures for further processing.

Remember to choose the approach that best suits your specific needs, considering factors such as readability, performance, and compatibility with your JavaScript version. Being able to efficiently remove empty strings from arrays empowers you to write cleaner code and enhances the reliability of your JavaScript applications.

If you have any questions, please leave a comment below.

Happy coding! 🙂

Leave a Reply