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?
We use the filter method to remove falsy values from an array. The filter method filters out all the values that return false when passed to a function. When you use filter and pass a Boolean constructor, you can quickly filter out all the falsy values from the array.
To remove the falsy values from an object, pass the object to the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete each falsy value from the object.
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. That is, all values are truthy except false , 0 , -0 , 0n , "" , null , undefined , and NaN .
Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.
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 !!
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With