admin管理员组

文章数量:1323335

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 ]

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 ]
Share Improve this question asked Aug 17, 2016 at 21:10 jruivojruivo 4971 gold badge8 silver badges23 bronze badges 3
  • NaN == NaN //false Use Number.isNaN – VLAZ Commented Aug 17, 2016 at 21:12
  • Anyway, since NaN is a falsy value, you could just filter out, all falsy values – VLAZ Commented Aug 17, 2016 at 21:13
  • Possible duplicates: Filter null from an array in JavaScript and How to filter() out NaN, null, 0, false in an array (JS). – Henke - Нава́льный П с м Commented Mar 17, 2021 at 10:37
Add a ment  | 

3 Answers 3

Reset to default 7

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 ments, 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

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Since false, null, 0, "", undefined and NaN are all Falsy values in JavaScript therefore they will return false when tested.

function bouncer(arr) {
  var array = arr.filter(function(val){
    return val;
  });
  return array;
}

Only values which do not return false will be added to the array.

This question is same as this question.

本文标签: javascriptFiltering NaN from an arrayStack Overflow