I struggled finding the solution I was looking for in other stackoverflow posts, even though I strongly feel as if it must exist. If it does, please do forward me in the rig
const myData = [
{ team: "GSW", pts: 120 },
{ team: "HOU", pts: 100 },
{ team: "GSW", pts: 110 },
{ team: "SAS", pts: 135 },
{ team: "HOU", pts: 102 },
{ team: "SAS", pts: 127 },
{ team: "SAS", pts: 142 },
{ team: "GSW", pts: 125 }
];
var result = myData.reduce(function (a, b) {
var exist = -1;
//some breaks the loop once it gets the true
a.some((x, y) => {
if (x.team == b.team) {
//assigning index of existing object in array
exist = y;
return true;
} else {
return false;
}
});
if (exist == -1) {
a.push({ team: b.team, pts: b.pts, count: 1 });
} else {
a[exist].count += 1;
a[exist].pts += b.pts;
}
return a;
}, []).map(t => {return {team: t.team, avg: t.pts/t.count, count:t.count}});
console.log(result);