Remove Empty Strings From An Array In JavaScript

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.

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

remove empty strings from an array in 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.

Conclusion

In this article, you saw how to remove empty strings from an array in JavaScript. There are many ways to achieve this and which one you choose will depend on your use case.

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

Happy coding! πŸ™‚

Leave a Comment