Reputation: 952
Given:
var dic = {1: 11, 2: 22, 3:22, 4:44, 5:22};
How to find out efficiently the number of times 22
has been a value to a key in that set using jQuery?
Upvotes: 0
Views: 39
Reputation: 4261
var dic = {1: 11, 2: 22, 3:22, 4:44, 5:22};
var vals = Object.values(dic); //Gives [11, 22, 22, 44, 22]
Then, iterate over the array vals
var count = 0;
jQuery.each(vals, function(i,v) { if (v === 22) count++; });
At the end count will have the total occurrence of desired element
EDIT
Even the last line of code above can be put into a function:
function countElement(ele) {
var count = 0;
jQuery.each(vals, function(i,v) { if (v === ele) count++; });
return count;
}
And call it like:
countElement(22); //Gives 3
Upvotes: 1
Reputation: 312
you can loop and count,
arr22 = [];
$.each(dic,function(k,v){
if (v == 22) { arr22[arr22.length] = {k: v} }
})
arr22.length // length
Upvotes: 1