Group by count of objects within an array in Vanilla Javascript

前端 未结 3 1472
清酒与你
清酒与你 2021-01-29 00:17

I have an array of objects:

[{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}]

And I want to be able to return an

3条回答
  •  日久生厌
    2021-01-29 00:45

    You need to use simple for like below :

    var data = [{person:101, year: 2011}, 
                {person:102, year: 2012}, 
                {person:103, year: 2011}];
    
    
    var result = {},
      i;
    
    for(i=0; i < data.length; i++){
      let year = data[i].year;
      if(typeof result[year] === 'undefined'){
        result[year] = 1;
      }
      else{
        result[year] = result[year] + 1;
      }
    
    }
    
    console.log(result);
    

提交回复
热议问题