How do I remove empty elements from an array in JavaScript?
如何从JavaScript中删除数组中的空元素?
Is there a straightforward way, or do I need to loop through it and remove them manually?
是否有一种简单的方法,或者我需要对其进行循环并手动删除它们?
36 个解决方案
#1
463
I use this method, extending the native Array prototype:
我使用这个方法,扩展了本机数组原型:
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);
Or you can simply push the existing elements into other array:
或者您可以简单地将现有元素推到其他数组中:
// 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,,,,]);
#2
1059
Simple ways:
var arr = [1,2,,3,,3,null,,0,,undefined,4,,4,,5,,6,,,,];
// (filter - JS 1.6 and above)
arr = arr.filter(function(n){ return n != undefined });
arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]
//or - (only for arrays items which are numbers is numbers' strings)**
arr = arr.filter(Number) // [1, 3, 3, 4, 4, 5, 6]
// ES6 style (Firefox FTW)
arr.filter(n => true) // [1, 2, 3, 3, null, 0, undefined, 4, 4, 5, 6]
// or if "null" values are to be removed:
arr.filter(n => n)
or - (only for single array items of type "text")
或-(仅针对“文本”类型的单个数组项)
['','1','2',3,,'4',,undefined,,,'5'].join('').split('');
// output: ["1","2","3","4","5"]
or - Classic way: simple iteration
或者-经典的方法:简单的迭代。
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]
via jQuery:
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]
UPDATE - just another fast, cool way (using ES6):
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]
Remove empty values
['foo', '',, ' ', true, [], [1], {}, undefined].filter(String)
// ["foo", " ", true, [1], Object {}, undefined]
Remove falsely values
Another method that removes the "falsey"
values of empty string ""
, 0
and undefined
另一种方法去掉了空字符串的“falsey”值,即0和未定义的值。
[1, 2,, 3,, 3,undefined,,"",false,null,0,NaN, 4," ", 4,true, 5,, 6,,,,].filter(Boolean);
// [1, 2, 3, 3, 4, " ", 4, true, 5, 6]
#3
173
If you need to remove ALL empty values ("", null, undefined and 0):
如果需要删除所有空值(“”、null、未定义和0):
arr = arr.filter(function(e){return e});
To remove empty values and Line breaks:
删除空值和换行符:
arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});
Example:
例子:
arr = ["hello",0,"",null,undefined,1,100," "]
arr.filter(function(e){return e});
Return:
返回:
["hello", 1, 100, " "]
UPDATE (based on Alnitak's comment)
更新(基于Alnitak的评论)
In some situations you may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:
在某些情况下,您可能希望在数组中保留“0”,并删除其他任何东西(空、未定义和“”),这是一种方法:
arr.filter(function(e){ return e === 0 || e });
arr.filter(函数(e){return e == 0 || e});
Return:
返回:
["hello", 0, 1, 100, " "]
#4
118
Simply one liner:
只是一个衬套:
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
or using underscorejs.org:
或使用underscorejs.org:
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
#5
99
If you've got Javascript 1.6 or later you can use Array.filter
using a trivial return true
callback function, e.g.:
如果你有Javascript 1.6或更高版本,你可以使用数组。使用一个小的返回真回调函数来过滤。
arr = arr.filter(function() { return true; });
since .filter
automatically skips missing elements in the original array.
因为.filter会自动跳过原始数组中的缺失元素。
The MDN page linked above also contains a nice error-checking version of filter
that can be used in JavaScript interpreters that don't support the official version.
上面链接的MDN页面还包含一个不错的错误检查版本的过滤器,可以在不支持官方版本的JavaScript解释器中使用。
Note that this will not remove null
entries nor entries with an explicit undefined
value, but the OP specifically requested "missing" entries.
注意,这不会删除空条目或带有显式未定义值的条目,但是OP特别要求“丢失”条目。
#6
44
The clean way to do it.
清洁的方法。
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"]
#7
20
For removing holes, you should use
为了去除孔,你应该使用。
arr.filter(() => true)
For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:
对于删除孔,和,falsy (null,未定义,0,-0,NaN, ", false, document.all)值:
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]
#8
19
Simple ES6
简单ES6
['a','b','',,,'w','b'].filter(v => v);
#9
18
With Underscore/Lodash:
与强调/ 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.
请参见lodash文档。
#10
14
If using a library is an option I know underscore.js has a function called compact() http://documentcloud.github.com/underscore/ it also has several other useful functions related to arrays and collections.
如果使用库是一个选项,我知道下划线。js有一个名为compact()的函数:http://documentcloud.github.com/underscore/它还有其他一些与数组和集合相关的有用功能。
Here is an excerpt from their documentation:
以下是他们文件的摘录:
_.compact(array)
_.compact(数组)
Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.
返回带有所有假值的数组的副本。在JavaScript中,false、null、0、“”、未定义和NaN都是假的。
_.compact([0, 1, false, 2, '', 3]);
_.compact([0, 1, false, 2, ", 3]);
=> [1, 2, 3]
= >(1、2、3)
#11
12
@Alnitak
@Alnitak
Actually Array.filter works on all browsers if you add some extra code. See below.
其实数组。如果你添加了一些额外的代码,过滤器可以在所有的浏览器上运行。见下文。
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"]
This is the code you need to add for IE, but filter and Functional programmingis worth is imo.
这是您需要为IE添加的代码,但是过滤器和功能程序的价值是imo。
//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;
};
}
#12
12
Since nobody else mentioned it and most people have underscore included in their project you can also use _.without(array, *values);
.
因为没有人提到它,而且大多数人在他们的项目中都有下划线,你也可以使用_。没有(数组,*值);。
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
#13
7
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... ;)
你有了这个想法——你可以有其他类型的过滤功能。可能比你需要的多,但我觉得很慷慨……,)
#14
4
What about this(ES6) : To remove Falsy value from an array.
这个(ES6):从一个数组中移除Falsy值。
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"]
#15
3
I'm simply adding my voice to the above “call ES5's Array..filter()
with a global constructor” golf-hack, but I suggest using Object
instead of String
, Boolean
, or Number
as suggested above.
我只是简单地将我的声音添加到上面的“调用ES5的数组..filter()和一个全局构造函数”golf-hack中,但是我建议使用对象而不是字符串、布尔值或以上所建议的数字。
Specifically, ES5's filter()
already doesn't trigger for undefined
elements within the array; so a function that universally returns true
, which returns all elements filter()
hits, will necessarily only return non-undefined
elements:
具体地说,ES5的filter()已经不会触发数组中未定义的元素;因此,一个普遍返回true的函数,返回所有元素过滤器()命中,将只返回非未定义的元素:
> [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]
However, writing out ...(function(){return true;})
is longer than writing ...(Object)
; and the return-value of the Object
constructor will be, under any circumstances, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting, Object
is a short-hand for function(){return true}
.
但是,写出…(函数(){返回true;})比写…(对象)要长;在任何情况下,对象构造函数的返回值都是某种对象。与上面建议的原始构造函数不同,没有可能的对象值是falsey,因此在布尔设置中,对象是函数(){返回true}的短指针。
> [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]
#16
3
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
console.log(r)
[1,2,3]
(1、2、3)
#17
3
You should use filter to get array without empty elements. Example on ES6
您应该使用filter来获取没有空元素的数组。例子ES6
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
#18
2
What about that:
是什么:
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
#19
2
When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.
当使用上面的最高投票答案时,第一个例子,我获得了字符串长度大于1的单个字符。下面是我解决这个问题的方法。
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.
如果未定义,则返回如果长度大于0,则返回。希望能帮助别人。
Returns
返回
["some string yay", "Other string yay"]
#20
1
This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)
这是可行的,我在AppJet测试了它(你可以在它的IDE上复制代码,然后按“reload”来查看它的工作,不需要创建一个帐户)
/* 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]
*/
#21
1
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
与这里的其他解决方案相比,Chrome在Chrome上的速度要快2到50倍,Firefox的速度要快5到50倍,正如您在这里看到的:http://jsperf.com/remove-null- items-fromarray。
The code below adds the non-enumerable 'removeNull' method to the Array, which returns 'this' for daisy-chaining :
下面的代码将不可枚举的“removeNull”方法添加到数组中,该方法返回“this”用于daisyi -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 } ) ;
#22
1
foo = [0, 1, 2, "", , false, 3, "four", null]
foo.filter(function(e) {
return e === 0 ? '0' : e
})
returns
返回
[0, 1, 2, 3, "four"]
#23
1
'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.
“滥用”……(object-member)循环。=>只有truthy的值出现在循环体中。
// --- 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);
#24
1
This might help you : https://lodash.com/docs/4.17.4#remove
这可能会帮助您: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));
});
};
#25
0
Filtering out invalid entries with a regular expression
用正则表达式过滤无效的条目。
array = array.filter(/\w/);
filter + regexp
#26
0
The best way to remove empty elements, is to use Array.prototype.filter()
, as already mentioned in other answers.
删除空元素的最好方法是使用Array.prototype.filter(),就像其他答案中已经提到的那样。
Unfortunately, Array.prototype.filter()
is not supported by IE<9. If you still need to support IE8 or an even older version of IE, you could use the following polyfill to add support for Array.prototype.filter()
in these browsers :
不幸的是,Array.prototype.filter()不受IE<9的支持。如果您仍然需要支持IE8或更老版本的IE,您可以使用以下的polyfill来添加对这些浏览器中的Array.prototype.filter()的支持:
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;
};
}
#27
0
If anyone is looking for cleaning the whole Array or Object this might help.
如果有人想要清理整个数组或对象,这可能会有所帮助。
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);
Output:
输出:
Removes anything that is null
, undefined
, ""
, " "
, empty object
or empty array
删除任何null、未定义的、“”、“空对象或空数组”。
jsfiddle here
jsfiddle这里
#28
0
This one will only remove empty values and not falsey ones, which I think is more desirable.
这只会删除空的值,而不是falsey的值,我认为这是更可取的。
There is an option to also remove null values.
还可以选择删除空值。
This method should be much faster than using splice.
这种方法应该比使用splice快得多。
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;
#29
0
use filter to remove empty string in array.
使用过滤器来删除数组中的空字符串。
var s = [ '1,201,karthikeyan,K201,HELPER,karthikeyan.a@limitlessmobil.com,8248606269,7/14/2017,45680,TN-KAR24,8,800,1000,200,300,Karthikeyan,11/24/2017,Karthikeyan,11/24/2017,AVAILABLE\r',
'' ]
var newArr = s.filter(function(entry) { return entry.trim() != ''; })
console.log(newArr);
#30
-1
Nice ... very nice We can also replace all array values like this
不错的…很好,我们也可以替换所有的数组值。
Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
for( var i = 0; i < this.length; i++ )
{
if( this[i] == OldValue )
{
this[i] = newValue;
}
}
};
#1
463
I use this method, extending the native Array prototype:
我使用这个方法,扩展了本机数组原型:
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);
Or you can simply push the existing elements into other array:
或者您可以简单地将现有元素推到其他数组中:
// 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,,,,]);
#2
1059
Simple ways:
var arr = [1,2,,3,,3,null,,0,,undefined,4,,4,,5,,6,,,,];
// (filter - JS 1.6 and above)
arr = arr.filter(function(n){ return n != undefined });
arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]
//or - (only for arrays items which are numbers is numbers' strings)**
arr = arr.filter(Number) // [1, 3, 3, 4, 4, 5, 6]
// ES6 style (Firefox FTW)
arr.filter(n => true) // [1, 2, 3, 3, null, 0, undefined, 4, 4, 5, 6]
// or if "null" values are to be removed:
arr.filter(n => n)
or - (only for single array items of type "text")
或-(仅针对“文本”类型的单个数组项)
['','1','2',3,,'4',,undefined,,,'5'].join('').split('');
// output: ["1","2","3","4","5"]
or - Classic way: simple iteration
或者-经典的方法:简单的迭代。
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]
via jQuery:
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]
UPDATE - just another fast, cool way (using ES6):
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]
Remove empty values
['foo', '',, ' ', true, [], [1], {}, undefined].filter(String)
// ["foo", " ", true, [1], Object {}, undefined]
Remove falsely values
Another method that removes the "falsey"
values of empty string ""
, 0
and undefined
另一种方法去掉了空字符串的“falsey”值,即0和未定义的值。
[1, 2,, 3,, 3,undefined,,"",false,null,0,NaN, 4," ", 4,true, 5,, 6,,,,].filter(Boolean);
// [1, 2, 3, 3, 4, " ", 4, true, 5, 6]
#3
173
If you need to remove ALL empty values ("", null, undefined and 0):
如果需要删除所有空值(“”、null、未定义和0):
arr = arr.filter(function(e){return e});
To remove empty values and Line breaks:
删除空值和换行符:
arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});
Example:
例子:
arr = ["hello",0,"",null,undefined,1,100," "]
arr.filter(function(e){return e});
Return:
返回:
["hello", 1, 100, " "]
UPDATE (based on Alnitak's comment)
更新(基于Alnitak的评论)
In some situations you may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:
在某些情况下,您可能希望在数组中保留“0”,并删除其他任何东西(空、未定义和“”),这是一种方法:
arr.filter(function(e){ return e === 0 || e });
arr.filter(函数(e){return e == 0 || e});
Return:
返回:
["hello", 0, 1, 100, " "]
#4
118
Simply one liner:
只是一个衬套:
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
or using underscorejs.org:
或使用underscorejs.org:
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
#5
99
If you've got Javascript 1.6 or later you can use Array.filter
using a trivial return true
callback function, e.g.:
如果你有Javascript 1.6或更高版本,你可以使用数组。使用一个小的返回真回调函数来过滤。
arr = arr.filter(function() { return true; });
since .filter
automatically skips missing elements in the original array.
因为.filter会自动跳过原始数组中的缺失元素。
The MDN page linked above also contains a nice error-checking version of filter
that can be used in JavaScript interpreters that don't support the official version.
上面链接的MDN页面还包含一个不错的错误检查版本的过滤器,可以在不支持官方版本的JavaScript解释器中使用。
Note that this will not remove null
entries nor entries with an explicit undefined
value, but the OP specifically requested "missing" entries.
注意,这不会删除空条目或带有显式未定义值的条目,但是OP特别要求“丢失”条目。
#6
44
The clean way to do it.
清洁的方法。
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"]
#7
20
For removing holes, you should use
为了去除孔,你应该使用。
arr.filter(() => true)
For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:
对于删除孔,和,falsy (null,未定义,0,-0,NaN, ", false, document.all)值:
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]
#8
19
Simple ES6
简单ES6
['a','b','',,,'w','b'].filter(v => v);
#9
18
With Underscore/Lodash:
与强调/ 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.
请参见lodash文档。
#10
14
If using a library is an option I know underscore.js has a function called compact() http://documentcloud.github.com/underscore/ it also has several other useful functions related to arrays and collections.
如果使用库是一个选项,我知道下划线。js有一个名为compact()的函数:http://documentcloud.github.com/underscore/它还有其他一些与数组和集合相关的有用功能。
Here is an excerpt from their documentation:
以下是他们文件的摘录:
_.compact(array)
_.compact(数组)
Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.
返回带有所有假值的数组的副本。在JavaScript中,false、null、0、“”、未定义和NaN都是假的。
_.compact([0, 1, false, 2, '', 3]);
_.compact([0, 1, false, 2, ", 3]);
=> [1, 2, 3]
= >(1、2、3)
#11
12
@Alnitak
@Alnitak
Actually Array.filter works on all browsers if you add some extra code. See below.
其实数组。如果你添加了一些额外的代码,过滤器可以在所有的浏览器上运行。见下文。
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"]
This is the code you need to add for IE, but filter and Functional programmingis worth is imo.
这是您需要为IE添加的代码,但是过滤器和功能程序的价值是imo。
//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;
};
}
#12
12
Since nobody else mentioned it and most people have underscore included in their project you can also use _.without(array, *values);
.
因为没有人提到它,而且大多数人在他们的项目中都有下划线,你也可以使用_。没有(数组,*值);。
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
#13
7
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... ;)
你有了这个想法——你可以有其他类型的过滤功能。可能比你需要的多,但我觉得很慷慨……,)
#14
4
What about this(ES6) : To remove Falsy value from an array.
这个(ES6):从一个数组中移除Falsy值。
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"]
#15
3
I'm simply adding my voice to the above “call ES5's Array..filter()
with a global constructor” golf-hack, but I suggest using Object
instead of String
, Boolean
, or Number
as suggested above.
我只是简单地将我的声音添加到上面的“调用ES5的数组..filter()和一个全局构造函数”golf-hack中,但是我建议使用对象而不是字符串、布尔值或以上所建议的数字。
Specifically, ES5's filter()
already doesn't trigger for undefined
elements within the array; so a function that universally returns true
, which returns all elements filter()
hits, will necessarily only return non-undefined
elements:
具体地说,ES5的filter()已经不会触发数组中未定义的元素;因此,一个普遍返回true的函数,返回所有元素过滤器()命中,将只返回非未定义的元素:
> [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]
However, writing out ...(function(){return true;})
is longer than writing ...(Object)
; and the return-value of the Object
constructor will be, under any circumstances, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting, Object
is a short-hand for function(){return true}
.
但是,写出…(函数(){返回true;})比写…(对象)要长;在任何情况下,对象构造函数的返回值都是某种对象。与上面建议的原始构造函数不同,没有可能的对象值是falsey,因此在布尔设置中,对象是函数(){返回true}的短指针。
> [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]
#16
3
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
console.log(r)
[1,2,3]
(1、2、3)
#17
3
You should use filter to get array without empty elements. Example on ES6
您应该使用filter来获取没有空元素的数组。例子ES6
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
#18
2
What about that:
是什么:
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
#19
2
When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.
当使用上面的最高投票答案时,第一个例子,我获得了字符串长度大于1的单个字符。下面是我解决这个问题的方法。
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.
如果未定义,则返回如果长度大于0,则返回。希望能帮助别人。
Returns
返回
["some string yay", "Other string yay"]
#20
1
This works, I tested it in AppJet (you can copy-paste the code on its IDE and press "reload" to see it work, don't need to create an account)
这是可行的,我在AppJet测试了它(你可以在它的IDE上复制代码,然后按“reload”来查看它的工作,不需要创建一个帐户)
/* 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]
*/
#21
1
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
与这里的其他解决方案相比,Chrome在Chrome上的速度要快2到50倍,Firefox的速度要快5到50倍,正如您在这里看到的:http://jsperf.com/remove-null- items-fromarray。
The code below adds the non-enumerable 'removeNull' method to the Array, which returns 'this' for daisy-chaining :
下面的代码将不可枚举的“removeNull”方法添加到数组中,该方法返回“this”用于daisyi -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 } ) ;
#22
1
foo = [0, 1, 2, "", , false, 3, "four", null]
foo.filter(function(e) {
return e === 0 ? '0' : e
})
returns
返回
[0, 1, 2, 3, "four"]
#23
1
'Misusing' the for ... in (object-member) loop. => Only truthy values appear in the body of the loop.
“滥用”……(object-member)循环。=>只有truthy的值出现在循环体中。
// --- 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);
#24
1
This might help you : https://lodash.com/docs/4.17.4#remove
这可能会帮助您: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));
});
};
#25
0
Filtering out invalid entries with a regular expression
用正则表达式过滤无效的条目。
array = array.filter(/\w/);
filter + regexp
#26
0
The best way to remove empty elements, is to use Array.prototype.filter()
, as already mentioned in other answers.
删除空元素的最好方法是使用Array.prototype.filter(),就像其他答案中已经提到的那样。
Unfortunately, Array.prototype.filter()
is not supported by IE<9. If you still need to support IE8 or an even older version of IE, you could use the following polyfill to add support for Array.prototype.filter()
in these browsers :
不幸的是,Array.prototype.filter()不受IE<9的支持。如果您仍然需要支持IE8或更老版本的IE,您可以使用以下的polyfill来添加对这些浏览器中的Array.prototype.filter()的支持:
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;
};
}
#27
0
If anyone is looking for cleaning the whole Array or Object this might help.
如果有人想要清理整个数组或对象,这可能会有所帮助。
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);
Output:
输出:
Removes anything that is null
, undefined
, ""
, " "
, empty object
or empty array
删除任何null、未定义的、“”、“空对象或空数组”。
jsfiddle here
jsfiddle这里
#28
0
This one will only remove empty values and not falsey ones, which I think is more desirable.
这只会删除空的值,而不是falsey的值,我认为这是更可取的。
There is an option to also remove null values.
还可以选择删除空值。
This method should be much faster than using splice.
这种方法应该比使用splice快得多。
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;
#29
0
use filter to remove empty string in array.
使用过滤器来删除数组中的空字符串。
var s = [ '1,201,karthikeyan,K201,HELPER,karthikeyan.a@limitlessmobil.com,8248606269,7/14/2017,45680,TN-KAR24,8,800,1000,200,300,Karthikeyan,11/24/2017,Karthikeyan,11/24/2017,AVAILABLE\r',
'' ]
var newArr = s.filter(function(entry) { return entry.trim() != ''; })
console.log(newArr);
#30
-1
Nice ... very nice We can also replace all array values like this
不错的…很好,我们也可以替换所有的数组值。
Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
for( var i = 0; i < this.length; i++ )
{
if( this[i] == OldValue )
{
this[i] = newValue;
}
}
};