Filter null from an array in JavaScript

后端 未结 4 1529
予麋鹿
予麋鹿 2020-12-16 09:18

I have a task to remove false, null, 0, "", undefined, and NaN elements from an given array. I worked on a solution which removes all except null. Anyone can expla

相关标签:
4条回答
  • 2020-12-16 10:01

    You can use Array.prototype.filter for truthy value check - see demo below:

    function bouncer(array) {
      return array.filter(function(e) {
        return e;
      });
    }
    
    console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

    0 讨论(0)
  • 2020-12-16 10:02

    It is a problem with NaN, because

    NaN !== NaN
    

    read more here: Testing against NaN.

    For filtering the values, you could check for truthyness.

    function bouncer(arr) {
        return arr.filter(Boolean);
    }
    
    console.log(bouncer([1, "", null, NaN, 2, undefined, 4, 5, 6]));

    0 讨论(0)
  • 2020-12-16 10:04

    Use

    function bouncer(arr) {
     return arr.filter(function(item){
       return !!item;
     });
    }
    
    console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

    0 讨论(0)
  • 2020-12-16 10:11

    Well, since all of your values are falsy, just do a !! (cast to boolean) check:

    [1,"", null, NaN, 2, undefined,4,5,6].filter(x => !!x); //returns [1, 2, 4, 5, 6]
    

    Edit: Apparently the cast isn't needed:

    [1,"", null, NaN, 2, undefined,4,5,6].filter(x => x);
    

    And the code above removes null just fine, it's NaN that's the problem. NaN !== NaN as Nina says in her answer.

    0 讨论(0)
提交回复
热议问题