Group by count of objects within an array in Vanilla Javascript

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

    Use a generic group by key reducer that will count the number of items in each group. I will take inspiration from a previous answer of mine. This function will return another function that act as a reducer, but you can always give it the key that you want as a parameter.

    const groupByCounter = key => (result,current) => {
      const item = Object.assign({},current);
      if (typeof result[current[key]] == 'undefined'){
        result[current[key]] = 1;
      }else{
        result[current[key]]++;
      }
      return result;
    };
    
    const data = [{person:101, year: 2012}, {person:102, year: 2012}, {person:103, year: 2013}];
    
    const group = data.reduce(groupByCounter('year'),{});
    console.log(group);

提交回复
热议问题