如何在JavaScript中删除数组中的空元素?

是否有一种简单的方法,或者我需要循环并手动删除它们?


当前回答

这是我清理空字段的解决方案。

从费用对象开始:仅获取可用属性(带贴图)筛选空字段(带筛选器)将结果解析为整数(带映射)

fees.map( ( e ) => e.avail ).filter( v => v!== '').map( i => parseInt( i ) );

其他回答

带下划线/Loddash:

一般使用情况:

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

有空:

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

无需参阅lodash文档。

只需一个衬垫:

[1, false, "", undefined, 2].filter(Boolean); // [1, 2]

或使用underscorejs.org:

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]

这是我清理空字段的解决方案。

从费用对象开始:仅获取可用属性(带贴图)筛选空字段(带筛选器)将结果解析为整数(带映射)

fees.map( ( e ) => e.avail ).filter( v => v!== '').map( i => parseInt( i ) );

另一种方法是利用数组的长度属性:将非空项打包到数组的“左侧”,然后减少长度。它是一种就地算法-不分配内存,对垃圾收集器来说太糟糕了-并且它具有非常好的最佳/平均/最坏情况行为。

与这里的其他解决方案相比,这个解决方案在Chrome上速度快2到50倍,在Firefox上速度快5到50倍http://jsperf.com/remove-null-items-from-array

下面的代码将不可枚举的“removeNull”方法添加到Array中,该方法为菊花链返回“this”:

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 } ) ;

那怎么办

js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6