Possible Duplicate:
Remove empty elements from an array in Javascript
I want to remove null
or empty elements from an array using jquery
var clientName= new Array();
clientName[0] = "jack";
clientName[1] = "";
clientName[2] = "john";
clientName[2] = "peter";
Please give some suggestions.
we will use jquery array filter function for remove empty or null value. in filter function we will return values if string value is not empty or null value. return el != null && el !=
In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function. array.
To remove empty elements from a JavaScript Array, the filter() method can be used, which will return a new array with the elements passing the criteria of the callback function.
Answer: Use the filter() Method You can simply use the filter() method to remove empty elements (or falsy values) from a JavaScript array. A falsy value is a value that is considered false in a Boolean context. Falsy values in JavaScript includes an empty string "" , false , 0 , null , undefined , and NaN .
Use the jquery grep function, it'll identify array elements that pass criteria you define
arr = jQuery.grep(arr, function(n, i){
return (n !== "" && n != null);
});
There is no need in jQuery, use plain JavaScript (it is faster!):
var newArray = [];
for (var i = 0; i < clientname.length; i++) {
if (clientname[i] !== "" && clientname[i] !== null) {
newArray.push(clientname[i]);
}
}
console.log(newArray);
Another simple solution for modern browsers (using Array filter()
method):
clientname.filter(function(value) {
return value !== "" && value !== null;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With