Group by count of objects within an array in Vanilla Javascript

前端 未结 3 1471
清酒与你
清酒与你 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:46

    As others have mentioned, an object would be a better fit for aggregating the data. You could use a normal loop, or reduce to do it:

    var data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103,
    year: 2013}];
    
    var yearCounts = data.reduce(function (result, person) {
      var currentCount = result[person.year] || 0;
      result[person.year] = currentCount + 1;
      return result;
    }, {});
    
    console.log(yearCounts);

    If you really need it as an array, you could the loop over the object and convert it to an array:

    var data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103,
    year: 2013}];
    
    var yearCounts = data.reduce(function (result, person) {
      var currentCount = result[person.year] || 0;
      result[person.year] = currentCount + 1;
      return result;
    }, {});
    
    var year,
      yearCountArray = [];
    for (year in yearCounts) {
      if (yearCounts.hasOwnProperty(year)) {
        yearCountArray.push({
          year: year,
          count: yearCounts[year]
        });
      }
    }
    
    console.log(yearCountArray);

提交回复
热议问题