我有一个像这样的数组:
const teams = [
{
name: 'team1',
goalsScored: 10,
goalsAgainst: 10,
points: 7
},
name: 'team2',
goalsScored: 12,
goalsAgainst: 9,
points: 6
},
name: 'team3',
goalsScored: 5,
goalsAgainst: 5,
points: 4
},
name: 'team4',
goalsScored: 3,
goalsAgainst: 10,
points: 0
},
]
我想对它进行排序: 第一个条件:更多分,如果相等则 第二个条件:更多进球得分,如果也等于则 第三个条件:更少的目标反对。
这部分很简单。我是这样的:
myGroup.sort((a, b) =>
a.points === b.points && a.goalsScored!==b.goalsScored ? b.goalsScored-a.goalsScored :
a.points === b.points && a.goalsScored===b.goalsScored ? a.goalsAgainst-b.goalsAgainst :
b.points-a.points
);
第四种情况更加困难,这就是我正在努力解决的问题。
我有一个对象来表示玩家和结果之间的所有游戏。
{
game1: [{ {rivals: ['team1', 'team2'], winner: "team2"} }],
game2: [{ {rivals: ['team1', 'team3'], winner: "team3"} }],
game3: [{ {rivals: ['team1', 'team4'], winner: "team4"} }],
game4: [{ {rivals: ['team2', 'team3'], winner: "team2"} }],
game5: [{ {rivals: ['team2', 'team4'], winner: "team4"} }],
game6: [{ {rivals: ['team3', 'team4'], winner: "none"} }],
}
因此,如果上述所有条件都得到满足(均分,GoalScored和GoalAgainst相等),我需要检查相等的球队,看看哪个在直接比赛中获胜。获胜者的排名较高,然后团队失手。 如果没有(没有)获胜者,那么我们保持原样。 这是我无法解决的第四部分。
谢谢您的帮助!
答案 0 :(得分:1)
看看compareGames
函数:
const compareGames = function (a,b) {
for (var game in games) {
var gameData = games[game][0];
if (gameData.rivals.indexOf(a.name)>=0 &&
gameData.rivals.indexOf(b.name)>=0) {
return (gameData.winner == b.name)
}
}
return false;
};
const games = {
game1: [{rivals: ['team1', 'team2'], winner: "team2"}],
game2: [{rivals: ['team1', 'team3'], winner: "team3"}],
game3: [{rivals: ['team1', 'team4'], winner: "team4"}],
game4: [{rivals: ['team2', 'team3'], winner: "team2"}],
game5: [{rivals: ['team2', 'team4'], winner: "team4"}],
game6: [{rivals: ['team3', 'team4'], winner: "none"}],
game7: [{rivals: ['team5', 'team6'], winner: "team5"}]
};
const myGroup = [
{
name: 'team5',
goalsScored: 9,
goalsAgainst: 11,
points: 8
},{
name: 'team6',
goalsScored: 9,
goalsAgainst: 11,
points: 8
},{
name: 'team4',
goalsScored: 9,
goalsAgainst: 11,
points: 9
},{
name: 'team1',
goalsScored: 10,
goalsAgainst: 10,
points: 10
},{
name: 'team3',
goalsScored: 9,
goalsAgainst: 10,
points: 9
},{
name: 'team2',
goalsScored: 10,
goalsAgainst: 10,
points: 9
}
];
myGroup.sort(function (a, b) {
//all the same
return a.points === b.points &&
a.goalsScored === b.goalsScored &&
a.goalsAgainst === b.goalsAgainst ?
compareGames(a,b) :
//same points
a.points === b.points &&
a.goalsScored!==b.goalsScored ?
b.goalsScored-a.goalsScored :
//same points and goals
a.points === b.points &&
a.goalsScored===b.goalsScored ?
a.goalsAgainst-b.goalsAgainst :
//default
b.points-a.points;
});
console.log(myGroup);