Remove all falsy values from an array

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

    This is my idea...

    function bouncer(arr) {
      // Don't show a false ID to this bouncer.
      var result = [];
      
        function isGood(obj){
          if(!Boolean(obj)){
            return false;
          } else {
            return true;
          }
        }
        
        for (var i=0; i < arr.length; i++){
          if (isGood(arr[i]) === true){
            result.push(arr[i]);
          }
        }
      return result;
    }
    
    console.log(bouncer([7, "ate", "", false, 9]));

    0 讨论(0)
  • 2020-11-28 07:45
    function bouncer(arr) {  
      var result = []; 
       for (var i = 0; i < arr.length; i++) {
         if (arr[i]) {
          result.push(arr[i]);
         }
       }
      return result;
     }
    
     bouncer([7, "ate", "", false, 9]);
    
    0 讨论(0)
  • 2020-11-28 07:46

    Using this simple filter will do:

    array.filter(Boolean)

    You can read more about Boolean here

    0 讨论(0)
  • 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...
    
    0 讨论(0)
  • 2020-11-28 07:47

    Try using filter and Boolean:

    let array = [7,"ate","",false,9];
    array.filter((values) => {return Boolean(values) === true })
    
    0 讨论(0)
  • 2020-11-28 07:50
    function bouncer(arr) {
    
        function filterFalse(value) {
            var a = Boolean(value);
            if (a === true) {
                return a;
            }
            return a;
        }
    
        function filterArray(x) {
            var y = filterFalse(x);
            if (y) {
                return true;
            } else {
                return false;
            }
        }
    
        var newArr = arr.filter(filterArray);
        return newArr;
    }
    
    bouncer([1, null, NaN, 2, undefined]);
    
    0 讨论(0)
提交回复
热议问题