Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - sort array of strings in a custom 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"}];

Order of an array items is not always the same. I want to sort that array so it goes like this: Goalkeeper, Full back, Centre back, Midfielder, Winger, Striker. I'm thinking about enums but I don't know how to use them in this situation.

like image 505
user7479651 Avatar asked Aug 24 '17 17:08

user7479651


1 Answers

You could take an object for the sort order and then sort by the 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);
like image 120
Nina Scholz Avatar answered Sep 21 '22 00:09

Nina Scholz