-1

I have an array like

[
   {date:'1/8/14',code:'AV-502'},
   {date:'1/8/14',code:'AV-501'},
   {date:'2/8/14',code:'AV-502'},
   {date:'2/8/14',code:'AV-501'},
   {date:'2/8/14',code:'AV-502'}
]

How can I get the count of each code for a date ie count of AV-502 for date 1/8/14 and the same for 2/8/14 and so on in jquery. The result needed is like

[
       {date:'1/8/14',code:'AV-502',count:2},
       {date:'1/8/14',code:'AV-501',count:3},
       {date:'2/8/14',code:'AV-501',count:5}
]
I'm nidhin
  • 2,592
  • 6
  • 36
  • 62

2 Answers2

1

Try this:

var getCount = function (date, code) {
    var count = 0;
    $.each(arr, function (key, val) {
        if (val.date === date && val.code === code) {
            count++;
        }
    });
    return count;
}

//call this function
getCount('1/8/14', 'AV-502');
Mohit Pandey
  • 3,679
  • 7
  • 26
  • 38
1

You loop through and count them.

You have a bunch of options for how you loop through and count them. Several are described in this question and its answers.

In addition to those, there's the ES5 Array#reduce function:

var count = yourArray.reduce(function(prev, entry) {
    return entry.code === "AV-502" ? prev + 1 : prev;
}, 0);
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875