Lets say I have this array of objects:
const arrayOfObjects = [
{ task: "work", time: 1 },
{ task: "travel", time: 4 },
{ task: "work", time: 5 },
{ task: "eat", time: 3 },
{ task: "eat", time: 1 },
{ task: "eat", time: 5 }
];
and I want to return a single objects that returns each key as the task and each value as the sum of all values of the key.
for example, the produced object of the array above should be:
sumOfObejcts = {
work: 6,
travel: 4,
eat: 9
}
How can I do it properly with reduce function?
I don't know how to sum all the items of specific key, this is what I made after few tries from examples:
const sumOfObejcts = arrayOfObjects.reduce((acc, items) => {
let { task, time } = items;
return { ...acc, [task]: [...(acc[task] || []), time] };
}, {});
and the output I get is:
{
work: [1, 5],
travel: [4],
eat: [3, 1, 5]
}
So, I just want to return the sum of occurrence of the value instead.
question from:
https://stackoverflow.com/questions/65872353/how-to-sum-specific-element-in-reduce-object 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…