gpt4 book ai didi

Javascript - 以自定义方式对字符串数组进行排序

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:34 25 4
gpt4 key购买 nike

我有一个字符串数组:

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"}];

数组项的顺序并不总是相同的。我想对该数组进行排序,使其如下所示:守门员、后卫、中后卫、中场、边锋、前锋。我正在考虑枚举,但我不知道如何在这种情况下使用它们。

最佳答案

您可以将一个对象作为排序顺序,然后根据差异进行排序。

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);

关于Javascript - 以自定义方式对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com