Remove empty elements from an array in Javascript
如何从javascript中的数组中删除空元素?
有没有一个简单的方法,或者我需要循环通过它并手动删除它们?
简单方法:
1 2 3 4 5 6 7 8 9 10 11 | var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,]; arr.filter(n => n) // [1, 2, 3, -3, 4, 4, 5, 6] arr.filter(Number) // [1, 2, 3, -3, 4, 4, 5, 6] arr.filter(Boolean) // [1, 2, 3, -3, 4, 4, 5, 6] |
或-(仅适用于"文本"类型的单个数组项)
1 2 | ['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); // output: ["1","2","3","4","5"] |
或-经典方式:简单迭代
1 2 3 4 5 6 7 8 9 | var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,], len = arr.length, i; for(i = 0; i < len; i++ ) arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array arr.splice(0 , len); // cut the array and leave only the non-empty values arr // [1,2,3,3,[],Object{},5,6] |
< BR>
通过jQuery:1 2 3 4 5 | var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,]; arr = $.grep(arr,function(n){ return n == 0 || n }); arr // [1, 2, 3, 3, 0, 4, 4, 5, 6] |
< BR>
更新-只是另一种快速、酷的方式(使用ES6):1 2 3 4 5 6 7 8 9 10 | var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], temp = []; for(let i of arr) i && temp.push(i); // copy each non-empty value to the 'temp' array arr = temp; delete temp; // discard the variable arr // [1, 2, 3, 3, 4, 4, 5, 6] |
删除空值
1 2 3 | ['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String) // ["foo", null,"", 3, true, [1], Object {}, undefined, ()=>{}] |
编辑:这个问题在9年前得到了解答,当时
当然,我建议您使用
请记住,此方法将向您返回一个新数组,其中的元素通过您提供给它的回调函数的条件,例如,如果要删除
1 2 3 4 5 6 7 | var array = [0, 1, null, 2,"", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,]; var filtered = array.filter(function (el) { return el != null; }); console.log(filtered); |
它将取决于您认为是"空"的内容,例如,如果您处理的是字符串,上面的函数将不会删除空字符串的元素。
我看到经常使用的一种常见模式是删除不稳定的元素,其中包括空字符串
您可以简单地传递到
1 | var filtered = array.filter(Boolean); |
或
1 | var filtered = array.filter(function(el) { return el; }); |
这两种方法都有效,因为第一种情况下的
如果您使用的是稀疏数组,并且试图消除这些"漏洞",则只需使用
1 2 3 4 | var sparseArray = [0, , , 1, , , , , 2, , , , 3], cleanArray = sparseArray.filter(function () { return true }); console.log(cleanArray); // [ 0, 1, 2, 3 ] |
旧答案:不要这样做!
我使用此方法扩展本机数组原型:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Array.prototype.clean = function(deleteValue) { for (var i = 0; i < this.length; i++) { if (this[i] == deleteValue) { this.splice(i, 1); i--; } } return this; }; test = new Array("","One","Two","","Three","","Four").clean(""); test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]; test2.clean(undefined); |
也可以简单地将现有元素推送到其他数组中:
1 2 3 4 5 6 7 8 9 10 11 12 | // Will remove all falsy values: undefined, null, 0, false, NaN and"" (empty string) function cleanArray(actual) { var newArray = new Array(); for (var i = 0; i < actual.length; i++) { if (actual[i]) { newArray.push(actual[i]); } } return newArray; } cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]); |
如果需要删除所有空值(",空,未定义和0):
1 | arr = arr.filter(function(e){return e}); |
要删除空值和换行符:
1 2 3 4 5 | arr = arr.filter(function(e){ return e.replace(/( | | )/gm,"")}); |
例子:
1 2 | arr = ["hello",0,"",null,undefined,1,100,""] arr.filter(function(e){return e}); |
返回:
1 | ["hello", 1, 100,""] |
更新(基于Alnitak的评论)
在某些情况下,您可能希望在数组中保留"0"并删除任何其他内容(空、未定义和),这是一种方法:
1 | arr.filter(function(e){ return e === 0 || e }); |
返回:
1 | ["hello", 0, 1, 100,""] |
只需一个衬里:
1 | [1, false,"", undefined, 2].filter(Boolean); // [1, 2] |
或者使用underlinejs.org:
1 2 3 | _.filter([1, false,"", undefined, 2], Boolean); // [1, 2] // or even: _.compact([1, false,"", undefined, 2]); // [1, 2] |
如果您有javascript 1.6或更高版本,您可以使用一个简单的
1 | arr = arr.filter(function() { return true; }); |
由于
上面链接的MDN页面还包含一个不错的
请注意,这不会删除
干净利落的方法。
1 2 3 | 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"] |
要去除孔,应使用
1 2 | arr.filter(() => true) arr.flat(0) // Currently stage 3, check compatibility before using this |
用于删除hole,and,falsy(空,未定义,0,-0,nan,",false,document.all)值:
1 | arr.filter(x => x) |
用于删除孔、空值和未定义:
1 | arr.filter(x => x != null) |
1 2 3 4 | 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] |
简单ES6
1 | ['a','b','',,,'w','b'].filter(v => v); |
带下划线/深灰色:
一般用例:
1 2 | _.without(array, emptyVal, otherEmptyVal); _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); |
带空:
1 2 | _.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], ''); --> ["foo","bar","baz","foobar"] |
如无,请参阅罗达什文件。
如果使用库是一个选项,我知道underline.js有一个名为compact()的函数http://documentcloud.github.com/underline/,它还有一些与数组和集合相关的其他有用函数。
以下是他们文档的摘录:
_.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]
只需
1 | const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9]; |
简单方法:
1 | const clearArray = arr.filter( i => i ); |
@ Alnitak
实际上,如果添加一些额外的代码,array.filter可以在所有浏览器上工作。见下文。
1 2 3 4 5 6 7 8 9 | var array = ["","one",0,"",null,0,1,2,4,"two"]; function isempty(x){ if(x!=="") return true; } var res = array.filter(isempty); document.writeln(res.toJSONString()); // gives: ["one",0,null,0,1,2,4,"two"] |
这是您需要为IE添加的代码,但是过滤器和函数编程的价值在于IMO。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //This prototype is provided by the Mozilla foundation and //is distributed under the MIT license. //http://www.ibiblio.org/pub/Linux/LICENSES/mit.license if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisp*/) { var len = this.length; if (typeof fun !="function") throw new TypeError(); var res = new Array(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { var val = this[i]; // in case fun mutates this if (fun.call(thisp, val, i, this)) res.push(val); } } return res; }; } |
因为没有人提到它,而且大多数人在他们的项目中都有下划线,所以您也可以使用
1 2 | _.without(["text","string", null, null, null,"text"], null) // => ["text","string","text"] |
您可能会发现,与按照建议尝试循环和拼接相比,在数组上循环并从要保留的项中构建新的数组更容易,因为在循环时修改数组的长度可能会带来问题。
你可以这样做:
1 2 3 4 5 6 7 8 9 | function removeFalsyElementsFromArray(someArray) { var newArray = []; for(var index = 0; index < someArray.length; index++) { if(someArray[index]) { newArray.push(someArray[index]); } } return newArray; } |
实际上,这里有一个更通用的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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] |
你得到了这个想法-然后你可以有其他类型的过滤函数。可能比你需要的要多,但我觉得很慷慨…;)
这个(es6)怎么办:从数组中删除falsy值。
1 2 3 4 5 6 7 | 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"] |
您应该使用filter获取不包含空元素的数组。ES6实例
1 2 | const array = [1, 32, 2, undefined, 3]; const newArray = array.filter(arr => arr); |
1 | ES6: let newArr = arr.filter(e => e); |
当使用上面投票最高的答案时,第一个例子是,对于长度大于1的字符串,我得到单个字符。下面是我解决这个问题的方法。
1 2 | var stringObject = ["","some string yay","","","Other string yay"]; stringObject = stringObject.filter(function(n){ return n.length > 0}); |
如果未定义则不返回,如果长度大于0则返回。希望能帮助别人。
退换商品
1 | ["some string yay","Other string yay"] |
1 2 | var data = [null, 1,2,3]; var r = data.filter(function(i){ return i != null; }) |
1 | console.log(r) |
[1,2,3]
我只是把我的声音添加到上面的"呼叫ES5的
具体地说,ES5的
1 2 | > [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true}) [1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3] |
但是,写出
1 2 | > [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object) [1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3] |
那怎么办?
1 2 | js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',') 1,2,3,3,0,4,4,5,6 |
这是可行的,我在Appjet中测试了它(你可以复制粘贴代码到它的IDE上,然后按"重新加载"来查看它的工作,不需要创建帐户)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /* 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] */ |
"滥用"的…在(对象成员)循环中。=>循环体中只显示真实值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // --- 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); |
1 2 3 4 5 6 7 8 9 | var data= { myAction: function(array){ return array.filter(function(el){ return (el !== (undefined || null || '')); }).join(""); } }; var string = data.myAction(["I","am","","working","","on","","nodejs","" ]); console.log(string); |
输出:
I am working on nodejs
它将从数组中删除空元素并显示其他元素。
1 2 3 4 5 | foo = [0, 1, 2,"", , false, 3,"four", null] foo.filter(function(e) { return e === 0 ? '0' : e }) |
收益率
1 | [0, 1, 2, 3,"four"] |
这可能有助于您:https://lodash.com/docs/4.17.4删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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); |
1 2 3 4 5 | scope.removeEmptyDetails = function(details){ _.remove(details, function(detail){ return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price)); }); }; |
另一种方法是利用数组的length属性:将数组左侧的非空项打包,然后减少长度。它是一种就地算法——不分配内存,对垃圾收集器来说太糟糕了——而且它具有非常好的最佳/平均/最坏的情况行为。
与这里的其他解决方案相比,这个解决方案在Chrome上的速度要快2到50倍,在Firefox上的速度要快5到50倍,如您在这里看到的:http://jspef.com/remove-null-items-from-array
下面的代码将不可枚举的"removenull"方法添加到数组中,该方法返回"this"作为菊花链:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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 } ) ; |
另一种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function filter_array(test_array) { var index = -1, arr_length = test_array ? test_array.length : 0, resIndex = -1, result = []; while (++index < arr_length) { var value = test_array[index]; if (value) { result[++resIndex] = value; } } return result; } console.log(filter_array([NaN, 0, 15, false, -22, '',undefined, 47, null])); |
使用筛选器删除数组中的空字符串。
1 2 3 4 5 6 | var s = [ '1,201,karthikeyan,K201,HELPER,[email protected],8248606269,7/14/2017,45680,TN-KAR24,8,800,1000,200,300,Karthikeyan,11/24/2017,Karthikeyan,11/24/2017,AVAILABLE ', '' ] var newArr = s.filter(function(entry) { return entry.trim() != ''; }) console.log(newArr); |
这只会去除空值,而不是虚假值,我认为这更可取。
还有一个选项可以删除空值。
这种方法应该比使用拼接快得多。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function cleanArray(a, removeNull) { var i, l, temp = []; l = a.length; if (removeNull) { for (i = 0; i < l; i++) { if (a[i] !== undefined && a[i] !== null) { temp.push(a[i]); } } } else { for (i = 0; i < l; i++) { if (a[i] !== undefined) { temp.push(a[i]); } } } a.length = 0; l = temp.length; for (i = 0; i < l; i++) { a[i] = temp[i]; } temp.length = 0; return a; } var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '', 4, , 4, , 5, , 6, , , , ]; cleanArray(myArray); myArray; |
用正则表达式筛选出无效条目
1 2 | array = array.filter(/\w/); filter + regexp |
如果有人要清理整个数组或对象,这可能会有所帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | var qwerty = { test1: null, test2: 'somestring', test3: 3, test4: {}, test5: { foo:"bar" }, test6:"", test7: undefined, test8:"", test9: true, test10: [], test11: ["77","88"], test12: { foo:"foo", bar: { foo:"q", bar: { foo:4, bar:{} } }, bob: {} } } var asdfg = [,,"","","yyyy", 78, null, undefined,true, {}, {x:6}, [], [2,3,5]]; function clean_data(obj) { for (var key in obj) { // Delete null, undefined,"","" if (obj[key] === null || obj[key] === undefined || obj[key] ==="" || obj[key] ==="") { delete obj[key]; } // Delete empty object // Note : typeof Array is also object if (typeof obj[key] === 'object' && Object.keys(obj[key]).length <= 0) { delete obj[key]; } // If non empty object call function again if(typeof obj[key] === 'object'){ clean_data(obj[key]); } } return obj; } var objData = clean_data(qwerty); console.log(objData); var arrayData = clean_data(asdfg); console.log(arrayData); |
输出:
删除
在这里闲逛
删除空元素的最佳方法是使用
不幸的是,ie<9不支持
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } |
下面是使用variadic behavior&es2015 fat arrow表达式的示例:
1 2 3 4 5 6 7 8 9 | Array.prototype.clean = function() { var args = [].slice.call(arguments); return this.filter(item => args.indexOf(item) === -1); }; // Usage var arr = ["", undefined, 3,"yes", undefined, undefined,""]; arr.clean(undefined); // ["", 3,"yes",""]; arr.clean(undefined,""); // [3,"yes"]; |
很好…很不错的我们还可以像这样替换所有数组值
1 2 3 4 5 6 7 8 9 10 | Array.prototype.ReplaceAllValues = function(OldValue,newValue) { for( var i = 0; i < this.length; i++ ) { if( this[i] == OldValue ) { this[i] = newValue; } } }; |
这是另一种方法:
1 2 | var arr = ["a","b", undefined, undefined,"e", undefined,"g", undefined,"i","","k"] var cleanArr = arr.join('.').split(/\.+/); |
我需要做同样的工作,然后就想到了这个问题。最后,我使用数组"join"创建了一个使用"u"分隔符的字符串,然后做了一点regex来:
1 2 3 | 1. replace"__" or more with just one"_", 2. replace preceding"_" with nothing"" and similarly 3. replace and ending"_" with nothing"" |
…然后使用数组"split"创建清理后的数组:
1 2 3 4 5 6 7 8 9 10 11 | var myArr = new Array("","","a","b","","c","","","","","","","","","e",""); var myStr =""; myStr = myArr.join("_"); myStr = myStr.replace(new RegExp(/__*/g),"_"); myStr = myStr.replace(new RegExp(/^_/i),""); myStr = myStr.replace(new RegExp(/_$/i),""); myArr = myStr.split("_"); alert("myArr=" + myArr.join(",")); |
…或在一行代码中:
1 2 3 4 5 | var myArr = new Array("","","a","b","","c","","","","","","","","","e",""); myArr = myArr.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_"); alert("myArr=" + myArr.join(",")); |
…或者,扩展数组对象:
1 2 3 4 5 6 7 | Array.prototype.clean = function() { return this.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_"); }; var myArr = new Array("","","a","b","","c","","","","","","","","","e",""); alert("myArr=" + myArr.clean().join(",")); |
这样做怎么样
1 2 3 4 5 | // Removes all falsy values arr = arr.filter(function(array_val) { // creates an anonymous filter func var x = Boolean(array_val); // checks if val is null return x == true; // returns val to array if not null }); |
试试这个。将数组传递给它,它将返回并删除空元素。*更新以解决Jason指出的错误
1 2 3 4 5 6 7 8 | function removeEmptyElem(ary) { for (var i = ary.length - 1; i >= 0; i--) { if (ary[i] == undefined) { ary.splice(i, 1); } } return ary; } |