I'm trying to remove all falsy values from an array.
I know this might not be the optimal solution for this problem but considering that I want to use the switch, is there a way to remove the NaN?
function bouncer(arr) {
arr=arr.filter(removeFalsy);
return arr;
}
function removeFalsy(val){
switch(val){
case false: return false;
case null: return false;
case 0: return false;
case "" :return false;
case undefined: return false;
case NaN: return false; // <=== NaN
default: return true;
}
}
bouncer([false, null, 0, NaN, undefined, ""]);
//result is: [ NaN ]
bouncer([1, null, NaN, 2, undefined]);
//result is: [ 1, NaN, 2 ]
Sometimes you just need to keep it simple:
function bouncer(arr) {
return arr.filter(Boolean);
}
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
console.log(bouncer([1, null, NaN, 2, undefined]));
NaN is not equal to anything, therefore you need to use Number.isNaN.
As explained in the comments, the global isNaN is not a good idea.
Thanks for pointing that out.
For an example see how-do-you-have-a-nan-case-in-a-switch-statement
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