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

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

    It can be simply done as follows.

    Note: Used JSON.parse and stringify to deep shallow copy the data. Or else the original array gets modified. Its not needed if the original array can be modified.

    const data = [
        {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}
     ];
    
    function groupData(mydata,keys)
    {
        var accresult = mydata.reduce(function(acc, value){
          var arr = acc.filter(function(obj){return obj.team==value.team});
          arr.length ? (item=arr[0] , keys.forEach(function(key){ item[key]+=value[key]; })) : acc.push(value);
          return acc;
      },[]);
    
      var result = accresult.map(function(val){
          var l = mydata.filter(function(obj){return obj.team==val.team}).length;
          keys.forEach(function(key){ val[key]=(val[key]/l).toFixed(2); })
          return val;
      });
      return result;
    }
    
    console.log(groupData(JSON.parse(JSON.stringify(data.slice(0))),['pts','ast']));
    console.log(groupData(JSON.parse(JSON.stringify(data.slice(0))),['pts','ast','reb']));
    console.log(groupData(JSON.parse(JSON.stringify(data.slice(0))),['pts']));

提交回复
热议问题