Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove null values from an array using jquery [duplicate]

Tags:

arrays

jquery

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.

like image 714
Kumaran Avatar asked Oct 05 '12 11:10

Kumaran


People also ask

How to remove null values in jquery?

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 !=

How do you remove blanks from an array?

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.

How to remove empty list in array in JavaScript?

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.

How to remove empty string in an array in JS?

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 .


2 Answers

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);
});
like image 137
Hans Hohenfeld Avatar answered Sep 30 '22 22:09

Hans Hohenfeld


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;
});
like image 22
VisioN Avatar answered Sep 30 '22 23:09

VisioN