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?
Try using filter and Boolean:
You can use Boolean :
This is another equivalent, but illustrative, solution:
This code sample is illustrative because it indicates to a reader that the variable
value
will be evaluated as truthy or falsey, and the anonymous function will return a boolean, eithertrue
orfalse
, mapping to the evaluation ofvalue
.For someone who is not familiar with this approach of removing values from an array based on their truthiness, or for someone who is not familiar with (or has not read the documentation on) the
filter
function, this example is the most concise that still conveys the behavior of thefilter
function.Of course, in your application you may opt for the more concise, yet less insightful, implementation:
lodash can do the trick nicely, there is a _.compact() function.