Remove empty elements from an array in Javascript

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

提交回复
热议问题