Given the following array:
const array = [
{
date: '2016-12-13T00:00:00.000Z',
stats: [
{
name: 'Soft Drinks',
sold: 34,
},
{
name: 'Snacks',
sold: 3,
},
{
name: 'Coffee and warm drinks',
sold: 26,
},
],
},
{
date: '2016-12-14T00:00:00.000Z',
stats: [
{
name: 'Soft Drinks',
sold: 34,
},
{
name: 'Snacks',
sold: 3,
},
{
name: 'Coffee and warm drinks',
sold: 26,
},
],
},
];
I would like to sum the sold values within the stats array. the final array should look like:
const array = [
stats: [
{
name: 'Soft Drinks',
sold: 68,
},
{
name: 'Snacks',
sold: 6,
},
{
name: 'Coffee and warm drinks',
sold: 52,
},
],
]
So basically like initiate over the array dates, sum up the stats of every day, If the name match then += the value.
I did so far:
const result = {};
array.forEach(
(item) => {
const { stats } = item;
stats.forEach((item) => {
Object
.keys(item)
.forEach((value) => {
result[value] = (result[value] || 0) + item[value];
});
});
});
console.log(result);
But I'm kinda lost at the second loop. What is the proper way to achieve the result?