Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering NaN from an array

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 ]
like image 754
jruivo Avatar asked Mar 01 '26 23:03

jruivo


2 Answers

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]));
like image 109
Amit Avatar answered Mar 03 '26 13:03

Amit


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

like image 30
ASDFGerte Avatar answered Mar 03 '26 11:03

ASDFGerte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!