Counting json array objects and create a new array with SUM result

I have a JSON array like this and,

const arrayVal = [{
    "DATE": "2020-12-1",
    "NAME": "JAKE",
    "TEAM_NO": 2,
    
}, {
    "DATE": "2020-12-1",
    "NAME": "ANNA",
    "TEAM_NO": 2,
    
}, {
    "DATE": "2020-12-1",
    "NAME": "JEFF",
    "TEAM_NO": 1,
    
}, {
    "DATE": "2020-12-1",
    "NAME": "ERIKA",
    "TEAM_NO": 2,
   
}, {
    "DATE": "2020-12-1",
    "NAME": "SUTTON",
    "TEAM_NO": 3,
}, {
    "DATE": "2020-12-1",
    "NAME": "ARNOLD",
    "TEAM_NO": 3,
     
}, {
    "DATE": "2020-12-2",
    "NAME": "JAKE",
    "TEAM_NO": 4,
     
}, {
    "DATE": "2020-12-2",
    "NAME": "ANNA",
    "TEAM_NO": 2,
     
}, {
    "DATE": "2020-12-2",
    "NAME": "JEFF",
    "TEAM_NO": 1,
     
}, {
    "DATE": "2020-12-2",
    "NAME": "ERIKA",
    "TEAM_NO": 3,
     
}, {
    "DATE": "2020-12-2",
    "NAME": "SUTTON",
    "TEAM_NO": 5,
     
}, {
    "DATE": "2020-12-2",
    "NAME": "ARNOLD",
    "TEAM_NO": 5,
     
}, {
    "DATE": "2020-12-3",
    "NAME": "JAKE",
    "TEAM_NO": 1,
     
}, {
    "DATE": "2020-12-3",
    "NAME": "ANNA",
    "TEAM_NO": 1,
     
}, {
    "DATE": "2020-12-3",
    "NAME": "JEFF",
    "TEAM_NO": 1,
     
}, {
    "DATE": "2020-12-3",
    "NAME": "ERIKA",
    "TEAM_NO": 2,
     
}, {
    "DATE": "2020-12-3",
    "NAME": "SUTTON",
    "TEAM_NO": 3,
     
}, {
    "DATE": "2020-12-3",
    "NAME": "ARNOLD",
    "TEAM_NO": 3,
      
}];

I am just trying to get below kind of reult out of above array. In this I want to count team numbers by day and create a new array with "TEAM_NO_COUNT" parameter.

[{
    "DATE": "2020-12-1",
    "TEAM_NO": 3, 
    "TEAM_NO_COUNT": 2, // 2 entries with no 3 team
     
}, {
    "DATE": "2020-12-1",
    "TEAM_NO": 1,
    "TEAM_NO_COUNT": 2,  // 2 entries with no 1 team
}, {
    "DATE": "2020-12-2",
    "TEAM_NO": 4,
    "TEAM_NO_COUNT": 1,  
}]

I have this code so far but it just give me a json object with counted team numbers, But It is not I want, I need above exact result.

TEAM_NO_COUNT = {}; // create an object
$.each(JSON.parse(JSON.stringify(arrayVal)), function (key, val) {

DATE_NO_CO = {};

  TEAM_NO_COUNT[val.DATE] = (TEAM_NO_COUNT[val.DATE] || {});

  TEAM_NO_COUNT[val.DATE][val.TEAM_NO] = (TEAM_NO_COUNT[val.DATE][val.TEAM_NO] || 0) + 1;
  
});

alert(JSON.stringify(TEAM_NO_COUNT));

Could someone please give me a help. It would be highly appreciated. Thanks.

15 thoughts on “Counting json array objects and create a new array with SUM result”

Leave a Comment