Languages
[Edit]
EN

JavaScript - remove empty strings from array without loop

0 points
Created by:
Iona
445

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' ]

See also

  1. JavaScript - remove empty elements from array

  2. JavaScript - remove empty strings from array

  3. JavaScript - Truthy and Falsy values

References

  1. Array.prototype.filter() - JavaScript | MDN
  2. Boolean - JavaScript | MDN
  3. Arrow function expressions - JavaScript | MDN

Alternative titles

  1. JavaScript - remove empty strings from array without using any loop
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join