我有一系列比赛结果,我需要根据得分确定为球队添加多少分。在本例中,法国队得 3 分,克罗地亚队得 0 分,英格兰队和西类牙队各得 1 分。如何实现这一点,有人可以帮忙吗?
const matches = [
{
homeTeam: 'France',
awayTeam: 'Croatia',
score: '2:1',
date: '18.01.2019'
},
{
homeTeam: 'England',
awayTeam: 'Spain',
score: '1:1',
date: '18.01.2019'
}
];
function getRankings(games) {
// ...implementation
}
const footbalRankings = getRankings(matches);
console.log(footbalRankings);
输出应该是这样的:
[
{ team: 'France', points: 3 }
{ team: 'England', points: 1 }
{ team: 'Spain', points: 1 }
{ team: 'Croatia', points: 0 }
]
最佳答案
const matches = [
{
homeTeam: 'France',
awayTeam: 'Croatia',
score: '2:1',
date: '18.01.2019'
}, {
homeTeam: 'England',
awayTeam: 'Spain',
score: '1:1',
date: '18.01.2019'
}
];
function getRankings(games) {
var ranks = {};
games.forEach(game => {
var [homeScore, awayScore] = game.score.split(':');
if (!ranks[game.homeTeam]) ranks[game.homeTeam] = { name: game.homeTeam, points: 0 };
if (!ranks[game.awayTeam]) ranks[game.awayTeam] = { name: game.awayTeam, points: 0 };
if (homeScore > awayScore) {
ranks[game.homeTeam].points += 3;
} else if (awayScore > homeScore) {
ranks[game.awayTeam].points += 3;
} else {
ranks[game.homeTeam].points++;
ranks[game.awayTeam].points++;
}
});
return Object.values(ranks).sort((a, b) => a.points > b.points ? -1 : 1);
}
var footbalRankings = getRankings(matches);
console.log(footbalRankings);
关于javascript - 如何判断哪队获胜,胜则加3分,输则加0,平则加1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633558/