首页 > 解决方案 > 节点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;
};

标签: arraysnode.js

解决方案


尝试使用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));


推荐阅读