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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With