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 false
, null
, 0
, ""
, 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 arr.filter(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.