How to remove empty elements from an array in JavaScript ?
Removing all the empty elements like null,0,'',"",undefined using function
function arr_filter(arr) {
var ind = -1,arr_len = arr ? arr.length : 0,resInd = -1,res = [];
while (++ind < arr_len) {
var val = arr[ind];
if (val) {
res[++resInd] = val;
}
}
return res;
}
Copy Code
We use this method, extending the native Array prototype :
Array.prototype.clean = function(deleteValue) {
for (var we = 0; we < 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);
Copy Code
Or we 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 we = 0; we < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
}
cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);
Copy Code
If we need to remove ALL empty values ("", null, undefined and 0):
arr = arr.filter(function(e){return e});
Copy Code
To remove empty values and Line breaks:
arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});
Copy Code Example:
arr = ["hello",0,"",null,undefined,1,100," "]
arr.filter(function(e){return e});
Copy Code
Output
["hello", 1, 100, " "]
Copy Code
Solution 4:
In some situations we may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:
arr.filter(function(e){ return e === 0 || e });
Copy Code Output
["hello", 0, 1, 100, " "]
Copy Code Here we can do this,
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
Copy Code or using underscorejs.org :
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
Copy Code
If you've got Javascript 1.6 or later we can use Array.filter using a trivial return true
callback function, e.g.:
arr = arr.filter(function() { return true; });
Copy Code Since .filter
automatically skips missing elements in the original array. 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. Note that this will not remove null
entries nor entries with an explicit undefined
value, but the OP specifically requested "missing" entries. 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"]
Copy Code