I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.
function bouncer(arr) {
arr = arr.filter(function (n) {
return (n !== undefined && n !== null && n !== false && n !== 0 && n !== "" && isNaN()!=NaN); });
return arr;
}
bouncer([7, "ate", "", false, 9, NaN], "");
The above is getting satisfied for all except the NaN test case. Can someone help me check in the array whether it contains NaN or not?
Since you want to get rid of "falsy" values, just let JavaScript do its thing:
The double-application of the
!
operator will make the filter callback returntrue
when the value is "truthy" andfalse
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. TheisNaN()
function returnstrue
if its parameter, when coerced to a number, isNaN
, andfalse
otherwise.)edit — note that
would work too as LoremIpsum notes in another answer, because the built-in Boolean constructor does pretty much the exact same thing as
!!
.Using this simple filter will do:
array.filter(Boolean)
You can read more about
Boolean
hereI know this can be done using the arr.filter() method. But I prefer using the Boolean() function. Is clearer to me. Here's how I did it, although a little longer:
I think a better deal this way
This should be what you are looking for:
This is my idea...