如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
如何在JavaScript中删除数组中的空元素?
是否有一种简单的方法,或者我需要循环并手动删除它们?
当前回答
另一种方法是利用数组的长度属性:将非空项打包到数组的“左侧”,然后减少长度。它是一种就地算法-不分配内存,对垃圾收集器来说太糟糕了-并且它具有非常好的最佳/平均/最坏情况行为。
与这里的其他解决方案相比,这个解决方案在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 } ) ;
其他回答
带下划线/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文档。
使用筛选器删除数组中的空字符串。
var s=['1201,karthikeyan,K201,直升机,karthikeyan.a@limitlessmobil.com,8248606269,7/14/201745680,TN-KAR24,88001000200300,Karthikeyan,2017年11月24日,Karthikey an,2017月11日,可用\r,'' ]var newArr=s.filter(函数(条目){return entry.trim()!=“”;})console.log(newArr);
这可能会帮助您:https://lodash.com/docs/4.17.4#remove
var details = [
{
reference: 'ref-1',
description: 'desc-1',
price: 1
}, {
reference: '',
description: '',
price: ''
}, {
reference: 'ref-2',
description: 'desc-2',
price: 200
}, {
reference: 'ref-3',
description: 'desc-3',
price: 3
}, {
reference: '',
description: '',
price: ''
}
];
scope.removeEmptyDetails(details);
expect(details.length).toEqual(3);
scope.removeEmptyDetails = function(details){
_.remove(details, function(detail){
return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
});
};
实际上,您可以使用ES6+方法,假设数组如下:
const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
答案可以是以下两种方式之一:
第一种方式:常量clearArray=arr.filter(i=>i);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]第二种方式:const clearArray=arr.filter(布尔值);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
2022年10月14日更新:
这两个答案并不完全正确,即使在给定的例子中,是的,它是有效的,但请注意给定数组中的数字0,通过这两种方式,数字0都会消失,这显然与使用布尔强制检查项目有关。
完全正确的方法是检查nulish并删除它们:
const notNil = (i) => !(typeof i === 'undefined' || i === null);
const clearArray = arr.filter(i => isNil(i));
常量arr=[1,2,3,未定义,4,5,6,未定义、7,8,未定义;未定义,0,9];常量notNil=(i)=>!(类型i===“未定义”||i===null);console.log(“非nil:”,arr.filter(非nil));
ES6:
let newArr = arr.filter(e => e);