Remove all falsy values from an array
You can use Boolean :
var myFilterArray = myArray.filter(Boolean);
Since you want to get rid of "falsy" values, just let JavaScript do its thing:
function bouncer(arr) {
return arr.filter(function(v) { return !!v; });
}
The double-application of the !
operator will make the filter callback return true
when the value is "truthy" and false
when it's "falsy".
(Your code is calling isNaN()
but not passing it a value; that's why that test didn't work for you. The isNaN()
function returns true
if its parameter, when coerced to a number, is NaN
, and false
otherwise.)
edit — note that
function bouncer(arr) {
return arr.filter(Boolean);
}
would work too as LoremIpsum notes in another answer, because the built-in Boolean constructor does pretty much the exact same thing as !!
.
truthyArray = arr.filter(el => el)
^ that's how you do it