Remove all falsy values from an array

后端 未结 22 3071
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 07:21

I would like to remove all falsy values from an array. Falsy values in JavaScript are false, null, 0, \"\", undefined, and NaN.



        
相关标签:
22条回答
  • 2020-11-28 08:01
    function bouncer(arr) {
    
    // Don't show a false ID to this bouncer.
    
    for (var i = 0; i < arr.length; i++) {
            if (!arr[i]) {
                arr.splice(i, 1);
                i = i-1;
            }
        }
        return arr;
    
    }
    
    bouncer([7, "ate", "", false, 9]);
    
    0 讨论(0)
  • 2020-11-28 08:03

    Thanks for all working answers above. Here are 3 approaches to solve the problem. Third solution addressed problem by your approach @Vignesh.

    1. 
    function bouncer(arr) {
      return arr.filter( function( val ){
            return val;
        });
    }
    
    2. 
    function bouncer(arr) {
    return arr.filter(Boolean);
    }
    3.
      function bouncer(arr) {
      return arr.filter(function(val){
          return val !== false && val !== "" && !(Number.isNaN(val)) && val !== 
    undefined && val !== 0 && val !== null;
        });
     }
    
    0 讨论(0)
  • 2020-11-28 08:04

    Using filter we can write

    function bouncer(arr) {
     return arr.filter(item => item);
    }
    bouncer([false, null, 0, NaN, undefined, ""]) // will return [].
    
    0 讨论(0)
  • 2020-11-28 08:08
    function falsy(value) {
          if (value) {
            return value;
          }
        }
    
        function bouncer(arr) {
          var filter = arr.filter(falsy);
          return filter;
        }
    
        bouncer([7, "ate", "", false, 9]);
    
    0 讨论(0)
提交回复
热议问题