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
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);