Skip to content

Remove falsy values from an array in JavaScript

How to remove falsy values from an array and retain only truthy values in JavaScript? Read on.

Falsy values in JavaScript are falsenull0""undefined, and NaN. The trick to remove these from an array is to use the filter method and filter the array by Boolean.

var arr = [2, "Anand", "", false, 15, 0, NaN, null, undefined];

//To filter false values just apply filter by Boolean


//Output would be -- [2. "Anand", 15]

The other way to do this is to write a function that checks if each of the array element is a falsy one and filter it. Like the one below.

See also  How to convert JavaScript Array to comma separated string?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.