我在下面的表格中有一组对象。每个对象代表足球比赛的结果。实际的数组包含的记录远远多于我在这里的记录。在每场比赛中,得分最高的球队(主场或客场)获得3分,得分最低的球队获得0分。如果得分相同,则每支球队获得1分。我想创建逻辑,聚合每个独特团队的积分,无论他们是在家还是离开。我想看到不同类型的选项(更新的语法等),尤其是一个vanilla javascript解决方案。
我也计划通过它,但我努力想出任何简洁的东西。
[{
"_id" : ObjectId("5a4824f3a469a068edc875e2"),
"homeTeam" : "Team1",
"homeScore" : 2,
"awayTeam" : "Team2",
"awayScore" : 1,
}
{
"_id" : ObjectId("5a4824f3a469a068edc894e9"),
"homeTeam" : "Team2",
"homeScore" : 2,
"awayTeam" : "Team3",
"awayScore" : 1,
},{
"_id" : ObjectId("5a4824f3a469a068edc554e7"),
"homeTeam" : "Team4",
"homeScore" : 1,
"awayTeam" : "Team5",
"awayScore" : 1,
}]
答案 0 :(得分:1)
var data = [{
"_id" : "5a4824f3a469a068edc875e2",
"homeTeam" : "Team1",
"homeScore" : 2,
"awayTeam" : "Team2",
"awayScore" : 1,
},
{
"_id" : "5a4824f3a469a068edc894e9",
"homeTeam" : "Team2",
"homeScore" : 2,
"awayTeam" : "Team3",
"awayScore" : 1,
},{
"_id" : "5a4824f3a469a068edc554e7",
"homeTeam" : "Team4",
"homeScore" : 1,
"awayTeam" : "Team5",
"awayScore" : 1,
}];
var teamStats = {};
var i = 0;
for(;i < data.length; i++) {
// New Home team
if(teamStats[data[i].homeTeam] == undefined) {
teamStats[data[i].homeTeam] = {
name: data[i].homeTeam,
score: 0
}
}
// New Away team
if(teamStats[data[i].awayTeam] == undefined) {
teamStats[data[i].awayTeam] = {
name: data[i].awayTeam,
score: 0
}
}
// Update score
teamStats[data[i].homeTeam].score += data[i].homeScore;
teamStats[data[i].awayTeam].score += data[i].awayScore;
}
// teamStats contains a scores of all teams