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 right direction.
I am trying to do a pretty standard group by in javascript using sports data. I have the following array of objects:
const myData = [
{team: "GSW", pts: 120, ast: 18, reb: 11},
{team: "GSW", pts: 125, ast: 28, reb: 18},
{team: "GSW", pts: 110, ast: 35, reb: 47},
{team: "HOU", pts: 100, ast: 17, reb: 43},
{team: "HOU", pts: 102, ast: 14, reb: 32},
{team: "SAS", pts: 127, ast: 21, reb: 25},
{team: "SAS", pts: 135, ast: 25, reb: 37},
{team: "SAS", pts: 142, ast: 18, reb: 27}
]
Each row in my data corresponds to the results of a specific basketball game. Simply put, I would like to group by the data, and apply a mean/average function to the grouped data. The results I would expect are:
const groupedData = [
{team: "GSW", pts: 118.3, ast: 27.0, reb: 25.3},
{team: "HOU", pts: 101, ast: 15.5, reb: 37.5},
{team: "SAS", pts: 134.7, ast: 21.3, reb: 29.7}
]
I would prefer to use vanilla javascript with reduce() here... given what I know about reduce, it seems like the best way. I am currently working on this and will post if i can get it to work before someone else posts the answer.
EDIT: My actual data has ~30 keys. I am hoping to find a solution that simply asks me to either (a) specify only the team column to be grouped by, and assume it groups the rest, or (b) pass an array of stat columns (pts, asts, etc.) rather than creating a line for each stat.
Thanks!