I have an array like this:
const fruits = [
{ fruit: 'apple', year: 2018 },
{ fruit: 'apple', year: 2018 },
{ fruit: 'banana', year: 2018 },
{ fruit: 'orange', year: 2018 },
{ fruit: 'apple', year: 2017 },
{ fruit: 'apple', year: 2016 }
];
Now I want to reduce this array to see how many fruits there are each year and how much the total is. So that the result looks like this:
const result = [
{ year: 2018, apple: 2, banana: 1, orange: 1 total: 4 },
{ year: 2017, apple: 1, total: 1 },
{ year: 2016, apple: 1, total: 1 }
];
I have tried with reduce, but I couldn't figure out how to group it based on the year. Maybe there is also a lodash helper?