Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of objects in array that match another object

right now I'm doing something like this to match objects in an array:

for (var key in users)
{
if (users[key].userID==session)
{
 //do whatever
}
}

but I need to figure out how many times this matches, if it only matches once, then I want it to trigger the event (where it says "//do whatever")

like image 752
Dylan Cross Avatar asked Jan 26 '26 12:01

Dylan Cross


2 Answers

This quits looking as soon it finds 2 matches

var count= 0;
for(var key in users){
    if(users[key].userID== session)++count;
    if(count== 2) break;
}
if(count== 1){
    //do whatever
}
like image 61
kennebec Avatar answered Jan 29 '26 00:01

kennebec


You could use the array.filter method like this:

users.filter(function(a){return (a.userID==session)}).length == 1;

Although the user will need to be running a modern browser (js 1.6) or the filter method be polyfilled.

like image 42
Sam Greenhalgh Avatar answered Jan 29 '26 02:01

Sam Greenhalgh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!