Reduce array of object to totals by property object
You need to return totals
after you modify it:
const src = [{mon:1,tue:0,wed:3,thu:5,fri:7,sat:0,sun:4}, {mon:5,tue:3,wed:2,thu:0,fri:1,sat:0,sun:6}];
const res = src.reduce((totals, item) => {
Object.keys(item).forEach(weekday => totals[weekday] = (totals[weekday] || 0) + item[weekday]);
return totals;
}, {});
console.log(res);
You need to return totals
as accumulator for reduce
.
If you have allways all days in the objects and you don't mind to mutate the first object, you could work without a start object.
const
src = [{ mon: 1, tue: 0, wed: 3, thu: 5, fri: 7, sat: 0, sun: 4 }, { mon: 5, tue: 3, wed: 2, thu: 0, fri: 1, sat: 0, sun: 6 }],
res = src.reduce((totals, item) =>
(Object.keys(item).forEach(d => totals[d] += item[d]), totals));
console.log(res);