Remove empty elements from an array in Javascript

后端 未结 30 2485
无人共我
无人共我 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:44

    'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.

    // --- Example ----------
    var field = [];
    
    field[0] = 'One';
    field[1] = 1;
    field[3] = true;
    field[5] = 43.68;
    field[7] = 'theLastElement';
    // --- Example ----------
    
    var originalLength;
    
    // Store the length of the array.
    originalLength = field.length;
    
    for (var i in field) {
      // Attach the truthy values upon the end of the array. 
      field.push(field[i]);
    }
    
    // Delete the original range within the array so that
    // only the new elements are preserved.
    field.splice(0, originalLength);
    
    0 讨论(0)
  • 2020-11-21 10:45

    Another way to do it is to take advantage of the length property of the array : pack the non-null items on the 'left' of the array, then reduce the length. It is an in-place algorithm -does not allocates memory, too bad for the garbage collector-, and it has very good best/average/worst case behaviour.

    This solution, compared to others here, is between 2 to 50 times faster on Chrome, and 5 to 50 times faster on Firefox, as you might see here : http://jsperf.com/remove-null-items-from-array

    The code below adds the non-enumerable 'removeNull' method to the Array, which returns 'this' for daisy-chaining :

    var removeNull = function() {
        var nullCount = 0           ;
        var length    = this.length ;
        for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
        // no item is null
        if (!nullCount) { return this}
        // all items are null
        if (nullCount == length) { this.length = 0; return this }
        // mix of null // non-null
        var idest=0, isrc=length-1;
        length -= nullCount ;                
        while (true) {
             // find a non null (source) slot on the right
             while (!this[isrc])  { isrc--; nullCount--; } 
             if    (!nullCount) { break }       // break if found all null
             // find one null slot on the left (destination)
             while ( this[idest]) { idest++  }  
             // perform copy
             this[idest]=this[isrc];
             if (!(--nullCount)) {break}
             idest++;  isrc --; 
        }
        this.length=length; 
        return this;
    };  
    
    Object.defineProperty(Array.prototype, 'removeNull', 
                    { value : removeNull, writable : true, configurable : true } ) ;
    
    0 讨论(0)
  • 2020-11-21 10:47

    For removing holes, you should use

    arr.filter(() => true)
    arr.flat(0) // Currently stage 3, check compatibility before using this
    

    For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:

    arr.filter(x => x)
    

    For removing hole, null, and, undefined:

    arr.filter(x => x != null)
    

    arr = [, null, (void 0), 0, -0, NaN, false, '', 42];
    console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, NaN, false, '', 42]
    console.log(arr.filter(x => x)); // [42]
    console.log(arr.filter(x => x != null)); // [0, -0, NaN, false, "", 42]

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

    What about this(ES6) : To remove Falsy value from an array.

    var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];
    
    arr.filter((v) => (!!(v)==true));
    
    //output:
    
    //[1, 2, "test", "false", true, 3, 4, 5, "end"]
    
    0 讨论(0)
  • 2020-11-21 10:49

    You may find it easier to loop over your array and build a new array out of the items you want to keep from the array than by trying to loop and splice as has been suggested, since modifying the length of the array while it is being looped over can introduce problems.

    You could do something like this:

    function removeFalsyElementsFromArray(someArray) {
        var newArray = [];
        for(var index = 0; index < someArray.length; index++) {
            if(someArray[index]) {
                newArray.push(someArray[index]);
            }
        }
        return newArray;
    }
    

    Actually here is a more generic solution:

    function removeElementsFromArray(someArray, filter) {
        var newArray = [];
        for(var index = 0; index < someArray.length; index++) {
            if(filter(someArray[index]) == false) {
                newArray.push(someArray[index]);
            }
        }
        return newArray;
    }
    
    // then provide one or more filter functions that will 
    // filter out the elements based on some condition:
    function isNullOrUndefined(item) {
        return (item == null || typeof(item) == "undefined");
    }
    
    // then call the function like this:
    var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
    var results = removeElementsFromArray(myArray, isNullOrUndefined);
    
    // results == [1,2,3,3,4,4,5,6]
    

    You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)

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

    With Underscore/Lodash:

    General use case:

    _.without(array, emptyVal, otherEmptyVal);
    _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
    

    With empties:

    _.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
    --> ["foo", "bar", "baz", "foobar"]
    

    See lodash documentation for without.

    0 讨论(0)
提交回复
热议问题