I'm sorting an array following JavaScript Array sort() Method. When I use a compareFunction
parameter, Internet Explorer 11 is not sorting properly.
I have a team array with players. These players have names:
var team = [
{name:"Waldo"},
{name:"Sarah"}
];
But I want to display them at the stadium video board sort by alphabetical order. So I have a list to append them when the DOM is ready:
MyHtml
<h2>My Team after sorting</h2>
<button onclick='sortAndDisplay()'>Click here to sort by Name</button>
<ul id="myTeamAfter">
</ul>
My Javascript code
function sortAndDisplay(){
$("#myTeamAfter").empty();
team.sort(function(a, b){return a.name > b.name;});
for(var i=0; i < team.length; i++){
$("#myTeamAfter").append( "<li>" + team[i].name + "</li>" );
}
}
Problem is that some Clubs use Internet Explorer 11 at their stadiums, and sort() function when I use my own compareFunction
is not working properly on IE11, so Waldo is displayed first than Sarah and the fans are confused.
I've created a Plunker where you can reproduce it:
Any idea to resolve the sort() for every browser?
Thanks!
Your comparer looks incorrect:
function(a, b){return a.name > b.name;}
This returns true
or false
, while it should return -1
, 0
or 1
depending on the ordering.
See How to sort strings in JavaScript (specifically localeCompare).
So code should be:
function sortAndDisplay() {
$("#myTeamAfter").empty();
team.sort(function(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
for (let i = 0; i < team.length; i++) {
$("#myTeamAfter").append("<li>" + team[i].name + "</li>");
}
}
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