节点js对象数组公共值总和

时间:2019-11-26 13:45:05

标签: arrays node.js

我有以下数组对象

var arrayteamscore = [{
                    Team: 'A team',
                    round: 'round 1',
                    score: 25,
                  }, {
                    Team: 'B team',
                    round: 'round 1',
                    score: 20,
                  },
                  {
                    Team: 'A team',
                    round: 'round 2',
                    score: 10,
                  }];

我希望获得每支球队的总得分,我希望得到下面的结果

 var arrayteamfinalscore = [{
                            Team: 'A team',
                            score: 35,
                            }, {
                            Team: 'B team',
                            score: 20,
                           },
                           ];

但由于无法确定如何完成操作,而卡在下面的代码中

 var total= function(arrayteamscore) {
 var total= 0,


 for (var i = 0; i < array.length; i++) {
total+= array[i].total;
 }

return total;
};

3 个答案:

答案 0 :(得分:2)

尝试使用reduce方法:

var arrayteamscore = [{
  Team: 'A team',
  round: 'round 1',
  score: 25,
}, {
  Team: 'B team',
  round: 'round 1',
  score: 20,
},
{
  Team: 'A team',
  round: 'round 2',
  score: 10,
}];

const result = arrayteamscore.reduce((a, {Team, round, score}) => {
  a[Team] = a[Team] || {Team, round, score: 0};
  a[Team].score += score;
  return a;
}, {})

console.log(Object.values(result));

答案 1 :(得分:2)

Object.values(
  arrayteamscore.reduce((acc, next) => {
    acc[next.Team] = acc[next.Team]
    ? { ...acc[next.Team], score: acc[next.Team].score + next.score }
    : next;

    return acc;
  }, {})
)

答案 2 :(得分:0)

function scoreAsObject(scores) {
  let response = {};
  for (let i = 0; i < scores.length; i++) {
    let teamName = scores[i]["Team"];
    if (response[teamName]) {
      response[teamName] = response[teamName] + scores[i]["score"];
    } else {
      response[teamName] = scores[i]["score"];
    }
  }
  return response;
}

function scoresAsArray(scoresAsObject) {
  let resp = Object.entries(scoresAsObject).reduce((agg, v, idx) => {
    agg.push({
      Team: v[0],
      score: v[1]
    });
    return agg;
  }, []);
  return resp;
};

console.log(scoresAsArray(scoreAsObject(scores)));