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

后端 未结 7 682
臣服心动
臣服心动 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

    You can do this by using reduce with Object.keys and Array.prototype.map as follows:-

    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 }
    ]
    
    let grpData = myData.reduce((acc, cv) => {
        if (!acc[cv.team]) {
            acc[cv.team] = {};
            acc[cv.team].team = cv.team;
            acc[cv.team].count = acc[cv.team].pts = acc[cv.team].ast = acc[cv.team].reb = 0
        }
        acc[cv.team].count++;
        acc[cv.team].pts += cv.pts;
        acc[cv.team].ast += cv.ast;
        acc[cv.team].reb += cv.reb;
        return acc;
    }, {});
    grpData = Object.keys(grpData).map(key => {
        let { team, reb, ast, pts, count } = grpData[key];
        return {
            team, reb: reb / count, ast: ast / count, pts: pts / count
        };
    })
    console.log(grpData);

提交回复
热议问题