Remove empty elements from an array in Javascript

后端 未结 30 2584
无人共我
无人共我 2020-11-21 09:53

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

相关标签:
30条回答
  • 2020-11-21 10:36

    Simple ES6

    ['a','b','',,,'w','b'].filter(v => v);
    
    0 讨论(0)
  • 2020-11-21 10:36

    Since nobody else mentioned it and most people have underscore included in their project you can also use _.without(array, *values);.

    _.without(["text", "string", null, null, null, "text"], null)
    // => ["text", "string", "text"]
    
    0 讨论(0)
  • 2020-11-21 10:37

    The clean way to do it.

    var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
    arr = arr.filter(Boolean);
    // [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]
    
    0 讨论(0)
  • 2020-11-21 10:37

    If using a library is an option I know underscore.js has a function called compact() http://documentcloud.github.com/underscore/ it also has several other useful functions related to arrays and collections.

    Here is an excerpt from their documentation:

    _.compact(array)

    Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

    _.compact([0, 1, false, 2, '', 3]);

    => [1, 2, 3]

    0 讨论(0)
  • 2020-11-21 10:37

    This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)

    /* appjet:version 0.1 */
    function Joes_remove(someArray) {
        var newArray = [];
        var element;
        for( element in someArray){
            if(someArray[element]!=undefined ) {
                newArray.push(someArray[element]);
            }
        }
        return newArray;
    }
    
    var myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
    
    print("Original array:", myArray2);
    print("Clenased array:", Joes_remove(myArray2) );
    /*
    Returns: [1,2,3,3,0,4,4,5,6]
    */
    
    0 讨论(0)
  • 2020-11-21 10:37
    foo = [0, 1, 2, "", , false, 3, "four", null]
    
    foo.filter(function(e) {
        return e === 0 ? '0' : e
    })
    

    returns

    [0, 1, 2, 3, "four"]
    
    0 讨论(0)
提交回复
热议问题