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

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

    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);

提交回复
热议问题