xxxxxxxxxx
arr.reduce((total, obj) => obj.credit + total,0)
// 3
xxxxxxxxxx
const arr = [ { 'name': 'P1', 'value': 150 }, { 'name': 'P1', 'value': 150 }, { 'name': 'P2', 'value': 200 }, { 'name': 'P3', 'value': 450 } ];
const sumByKey = (arr, key, value) => {
const map = new Map();
for(const obj of arr) {
const currSum = map.get(obj[key]) || 0;
map.set(obj[key], currSum + obj[value]);
}
const res = Array.from(map, ([k, v]) => ({[key]: k, [value]: v}));
return res;
}
console.log(sumByKey(arr, 'name', 'value')); // 'name' = value to group by, 'value' = value to sum
Run code snippet
xxxxxxxxxx
const fruits = [
{
type: "oranges",
amount: 10,
},
{
type: "apples",
amount: 0,
},
{
type: "oranges",
amount: 5,
},
];
const endresult = Array.from(
fruits
.reduce((map, curr) => {
if (!map.has(curr.type)) map.set(curr.type, { curr, count: 1 });
else {
map.get(curr.type).amount += curr.amount;
map.get(curr.type).count++;
}
return map;
}, new Map())
.values()
);
console.log(endresult);