I have an array like this:
const inputArray = [
{
userId: 1,
sum: 30,
},
{
userId: 1,
sum: 20,
},
{
userId: 2,
sum: 50,
},
{
userId: 2,
sum: 80,
},
];
Then I wrote a function that sums the values by key and got the following result:
const output = [
{
userId: 1,
sum: 50,
},
50,
{
userId: 2,
sum: 130,
},
130,
];
How can this error be corrected? Function code below:
const output = inputArray.reduce((accumulator, currentItem) => {
const index = accumulator.findIndex((item) => item.userId === currentItem.userId);
if (index < 0) {
return [...accumulator, currentItem];
} else {
return [...accumulator, (accumulator[index].sum += currentItem.sum)];
}
}, []);