Remove all falsy values from an array

后端 未结 22 3070
隐瞒了意图╮
隐瞒了意图╮ 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 07:53

    I see you never accepted an answer. Is the problem that you are relying on Logger.log or console.log to see if the null removal worked? I think the filter suggested by @LoremIpsum is the cleanest solution.

      const src2DArr = [[34], [75], [30], [48], [976], [], [178], [473], [51], [75], [29], [47], [40]];
      Logger.log("src2DArr: " +JSON.stringify(src2DArr)); 
      // [[34],[75],[30],[48],[976],[],[178],[473],[51],[75],[29],[47],[40]]
      
      var src2DArr1 = src2DArr.filter(Boolean);
      Logger.log("src2DArr1: " + JSON.stringify(src2DArr1));
      // [[34],[75],[30],[48],[976],[],[178],[473],[51],[75],[29],[47],[40]] 
    
    0 讨论(0)
  • 2020-11-28 07:54

    Just negate twice to "cast" to boolean. !NaN === true => !!NaN === false

        const truthy = arr.filter(o => !!o)
    
    0 讨论(0)
  • 2020-11-28 07:56

    You can use Boolean :

    var myFilterArray = myArray.filter(Boolean);
    
    0 讨论(0)
  • 2020-11-28 07:57

    bouncer function:

    function bouncer(arr) {
      return arr.filter((val) => {
        return !!val;
      });
    }
    
    console.log(bouncer([7, "ate", "", false, 9]));

    0 讨论(0)
  • 2020-11-28 07:58
    myArray = [false, null, 0, NaN, undefined, ""];
    myArray.map(item => {
    //if you want you can write logic
            console.log(item);
        })
        // Get rid of bad values
        .filter(Boolean);
    

    it will return [].

    0 讨论(0)
  • 2020-11-28 07:59

    I think a better deal this way

       function bouncer(arr) {
            arr = arr.filter(function(item) {
                return item;
            return arr;
    
        bouncer([7, "ate", "", false, 9, NaN, undefined, 0]);
    
    0 讨论(0)
提交回复
热议问题