我有一个字符串数组:
var players = [{Name: player1name, Surname: player1surname, Position: "Centre back"}, {Name: player2name, Surname: player2surname, Position: "Striker"}, {Name: player3name, Surname: player3surname, Position: "Full back"}, {Name: player4name, Surname: player4surname, Position: "Goalkeeper"}, {Name: player5name, Surname: player5surname, Position: "Midfielder"}, {Name: player6name, Surname: player6surname, Position: "Winger"}];
数组项的顺序并不总是相同。 我想对那个数组进行排序所以它是这样的:守门员,后卫,中后卫,中场,边锋,前锋。 我正在考虑枚举,但我不知道在这种情况下如何使用它们。
答案 0 :(得分:5)
您可以为排序顺序获取一个对象,然后按差异排序。
var players = ["Centre back", "Striker", "Full back", "Goalkeeper", "Midfielder", "Winger"],
order = { Goalkeeper: 1, 'Full back': 2, 'Centre back': 3, Midfielder: 4, Winger: 5, Striker: 6 };
players.sort(function (a, b) {
return order[a] - order[b];
});
console.log(players);

答案 1 :(得分:0)
你去吧。你应该使用这种方法。 您需要创建排名映射,然后按该映射排序。
let players = [
{
"name": "Molla Wague",
"position": "Centre-Back",
"jerseyNumber": 13,
"dateOfBirth": "1991-02-21",
"nationality": "Mali",
"contractUntil": "2018-06-30",
"marketValue": null
},
{
"name": "Heurelho Gomes",
"position": "Keeper",
"jerseyNumber": 1,
"dateOfBirth": "1981-02-15",
"nationality": "Brazil",
"contractUntil": "2019-06-30",
"marketValue": null
},
{
"name": "Christian Kabasele",
"position": "Centre-Back",
"jerseyNumber": 27,
"dateOfBirth": "1991-02-24",
"nationality": "Belgium",
"contractUntil": "2021-06-30",
"marketValue": null
},
{
"name": "José Holebas",
"position": "Left-Back",
"jerseyNumber": 25,
"dateOfBirth": "1984-06-27",
"nationality": "Greece",
"contractUntil": "2020-06-30",
"marketValue": null
},
{
"name": "Daryl Janmaat",
"position": "Right-Back",
"jerseyNumber": 2,
"dateOfBirth": "1989-07-22",
"nationality": "Netherlands",
"contractUntil": "2020-06-30",
"marketValue": null
},
{
"name": "Étienne Capoue",
"position": "Defensive Midfield",
"jerseyNumber": 29,
"dateOfBirth": "1988-07-11",
"nationality": "France",
"contractUntil": "2019-06-30",
"marketValue": null
},
{
"name": "Tom Cleverley",
"position": "Central Midfield",
"jerseyNumber": 8,
"dateOfBirth": "1989-08-12",
"nationality": "England",
"contractUntil": "2022-06-30",
"marketValue": null
},
{
"name": "Roberto Pereyra",
"position": "Attacking Midfield",
"jerseyNumber": 37,
"dateOfBirth": "1991-01-07",
"nationality": "Argentina",
"contractUntil": "2021-06-30",
"marketValue": null
},
{
"name": "Troy Deeney",
"position": "Centre-Forward",
"jerseyNumber": 9,
"dateOfBirth": "1988-06-29",
"nationality": "England",
"contractUntil": "2021-06-30",
"marketValue": null
}
];
const rankMap = {
'Keeper': 1,
'Centre-Back': 2,
'Right-Back': 3,
'Left-Back': 4,
'Defensive Midfield': 5,
'Central Midfield': 6,
'Attacking Midfield': 7,
'Right Wing': 8,
'Left Wing': 9,
'Centre-Forward': 10
};
players = players.sort((a, b) => rankMap[a.position] - rankMap[b.position]);
console.log(players);