Remove all falsy values from an array

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

    I know this can be done using the arr.filter() method. But I prefer using the Boolean() function. Is clearer to me. Here's how I did it, although a little longer:

    function bouncer(arr) {
    // Don't show a false ID to this bouncer.
    
        var falsy;
        var trueArr = [];
    
        for (i = 0; i < arr.length; i++) {
    
            falsy =  Boolean(arr[i]);
    
            if (falsy === true) {
    
            trueArr.push(arr[i]);
    
            }
    
        }
    
        return trueArr;
    }
    
    bouncer([7, "ate", "", false, 9]);
    // returns a new array that is filtered accordingly.
    

提交回复
热议问题