Javascript - sort an array of strings in your own way

I have an array of strings:

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

The order of the elements in the array is not always the same. I want to sort this array so that it looks like: Goalkeeper, Full back, Center back, Midfielder, Winger, Forward. I think of transfers, but I do not know how to use them in this situation.

+4
source share
1 answer

You can take an object for sorting order, and then sort by difference.

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);
Run codeHide result
+4
source

Source: https://habr.com/ru/post/1684401/


All Articles