Reputation: 15
How to count Array where value=1 inside jQuery.each?
This is my Array: result[index].isopen
This is my Code:
jQuery.each(result, function(index, item) {
console.log(result[index].isopen);
)};
This is the console.log:
0
1
1
How to create a var that counts the results where result[index].isopen
= 1?
In this case it will be 2.
Upvotes: 0
Views: 377
Reputation: 157
You can create a variable before the jQuery.each
line and increment it:
var openCount = 0;
jQuery.each(result, function(index, item) {
if (item.isopen) {
openCount++;
}
});
console.log(openCount);
You also need to fix your closing line of the each from )};
to });
You can also just do this with vanilla JS using the filter
function to filter the items and then check the length of the filtered array:
var openResults = results.filter(function (item) {
return item.isopen;
});
console.log(openResults.length)
Upvotes: 0
Reputation: 6625
Just declare the variable before the loop and increment inside the loop.
var count = 0;
jQuery.each(result, function(index, item) {
if (item.isopen) {
count++;
}
});
console.log(count);
Upvotes: 1