Group by and calculate mean / average of properties in a Javascript array

后端 未结 7 687
臣服心动
臣服心动 2021-01-18 14:22

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

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 15:06

    Using array of statsFields and loop over those to create totals and later to get averages

    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}
     ]
     
     const statsFields = ['pts','ast','reb'];
     
     const teamsObject = myData.reduce((a,{team,...stats})=>{
       a[team] = a[team] || {team, games:0};
       a[team].games++
       statsFields.forEach(k=> a[team][k] = (a[team][k] || 0) + stats[k]);
       return a;
     },{});
     
     const res = Object.values(teamsObject).map(({games,...team})=>{
        // average for each field total/games
        statsFields.forEach(k=> team[k] = team[k]/games);    
        return team;
     })
     
     console.log(JSON.stringify(res))

提交回复
热议问题