arrays - 节点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;
};
解决方案
尝试使用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));
推荐阅读
- python-3.x - 检查用户是否已经投票,即使他们还没有投票,也会返回 true?
- jestjs - 方法“模拟”意味着在 1 个节点上运行。找到了 0 个
- scala - 使用 Try out of Exception 上下文
- java - java.lang.NullPointerException:ava.io.File android.content.Context.getCacheDir()' 为空
- c# - 文件 Designer.cs 错误地嵌套在解决方案资源管理器中,无法移动
- javascript - 无法从子进程获取管道流
- angular - 用于生产的 Angular 应用程序上的代理配置
- android - 转换 Observable
- > 列出
- cocoapods - Xcode:无法为 UIView 渲染和更新自动布局状态:代理崩溃
- c - 依赖 PATH_MAX 会导致溢出