EN
JavaScript - remove empty strings from array without loop
0
points
In this article, we would like to show you how to remove empty strings from an array without using any loop in JavaScript.
1. Using filter() with Boolean
In this example, we use filter() method with passed Boolean as an argument to check for truthy values. The empty strings ('', "", ``) are falsy values, so they will be removed.
// ONLINE-RUNNER:browser;
var array = ['a', '', 'b', "", 'c', ``];
array = array.filter(Boolean);
console.log(array); // [ 'a', 'b', 'c' ]
2. Using filter() with arrow function
In this example, we present an alternative solution using the arrow function as filter() method argument.
// ONLINE-RUNNER:browser;
var array = ['a', '', 'b', "", 'c', ``];
array = array.filter((element) => element);
console.log(array); // [ 'a', 'b', 'c' ]