Problem
In JavaScript, how do I remove empty members from an array?
Is there a simple way to do this, or would I have to cycle through everything and manually remove them?
Asked by Tamas Czinege
Solution #1
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]
– or (only for single array items of type “text”)
['','1','2',3,,'4',,undefined,,,'5'].join('').split('');
// output: ["1","2","3","4","5"]
or – The traditional method: 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]
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]
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;
arr // [1, 2, 3, 3, 4, 4, 5, 6]
['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)
// ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}]
Answered by 31 revs, 7 users 77%
Solution #2
EDIT: This topic was answered about nine years ago, when the Array.prototype didn’t have many useful built-in methods.
Now, without a doubt, I would advise you to use the filter approach.
Keep in mind that this method will return a new array containing the entries that satisfy the callback function’s criteria.
If you wish to eliminate null or undefined values, for example:
It depends on what you mean by “empty.” If you’re working with strings, for example, the above code won’t eliminate elements that are empty strings.
One typical pattern that I see often used is to remove elements that are falsy, which include an empty string “”, 0, NaN, null, undefined, and false.
You can send the Boolean constructor function to the filter method or return the same element in the filter criteria function, for example:
var filtered = array.filter(Boolean);
Or
var filtered = array.filter(function(el) { return el; });
This works in both cases because the filter method calls the Boolean constructor as a function in the first case, converting the value, and in the second case, the filter method implicitly converts the callback’s return value to Boolean.
If you’re working with sparse arrays and want to remove the “holes,” you can use the filter function with a callback that returns true, such as:
Don’t do it, as the old adage goes.
This approach, which extends the native Array prototype, is what I use:
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);
Alternatively, you can just copy and paste the existing items into another 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,,,,]);
Answered by Christian C. Salvadó
Solution #3
If you want to get rid of all empty values (“”, null, undefined, and 0), do the following:
arr = arr.filter(function(e){return e});
To get rid of empty values and line breaks, do the following:
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 (as a result of Alnitak’s remark):
In some cases, you may wish to maintain “0” in the array while removing everything else (null, undefined, and “”); here’s how:
arr.filter(function(e){ return e === 0 || e });
Return:
["hello", 0, 1, 100, " "]
Answered by lepe
Solution #4
Simply one liner:
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
or using underscorejs.org:
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
Answered by Andreas Louv
Solution #5
If you have Javascript 1.6 or later, you can use Array.filter with a simple callback function, such as:
arr = arr.filter(function() { return true; });
because.filter skips any missing entries in the original array
A great error-checking version of filter may be found on the MDN page referenced above, which can be used in JavaScript interpreters that don’t support the official version.
The OP expressly specified “missing” entries, therefore this will not remove null or items with an explicit undefined value.
Answered by Alnitak
Post is based on https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript