Remove all falsy values from an array

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

    This should be what you are looking for:

    let array = [7, 'ate', '', false, 9, NaN];
    
    function removeFalsyItems(array) {
       // Your result
       let filter = array.filter(Boolean);
    
       // Empty the array
       array.splice(0, array.length);
    
       // Push all items from the result to our array
       Array.prototype.push.apply(array, filter);
    
       return array
    }
    
    removeFalsyItems(array) // => [7, 'ate', 9], funny joke btw...
    

提交回复
热议问题