Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  9] [ 6]  / answers: 1 / hits: 28208  / 11 Years ago, fri, august 23, 2013, 12:00:00

I know from the first look it sounds like duplicate question but i don't think it is...



I am receiving back a JSON array as:



var test1 = [] ;


or



var test2 = [{},{},{}] ;  //This is empty


I have no problem finding out if test1 is empty.



jQuery.isEmptyObject(test1)


My problem is with the test2...
Please note that in some cases the test2 might return something like:



var test2 = [{a:1},{},{}] ;  //All these are not empty
var test2 = [{},{a:1},{}] ; //All these are not empty
var test2 = [{},{},{a:1}] ; //All these are not empty


The above scenarios shouldn't be counted as empty.I've tried to use .length but it's not helping as the length is always 3... Any ideas?



Cheers.


More From » jquery

 Answers
172
function isArrayEmpty(array) {
return array.filter(function(el) {
return !jQuery.isEmptyObject(el);
}).length === 0;
}


jsFiddle Demo



Passes all of your tests.



A pure JavaScript solution would be to replace !jQuery.isEmptyObject(el) with Object.keys(el).length !== 0



Edit: Using Array.prototype.every



function isArrayEmpty(array) {
return array.every(function(el) {
return jQuery.isEmptyObject(el);
});
}

[#76192] Thursday, August 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parisc

Total Points: 438
Total Questions: 119
Total Answers: 119

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
;