This question already has an answer here:
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:
- Firefox 33.1 - Working!! :)
- Chrome 39.0.2171.65 - Working!! :)
- Internet Explorer 11.0.9600 - Not Working :(
Any idea to resolve the sort() for every browser?
Thanks!
Your comparer looks incorrect:
This returns
true
orfalse
, while it should return-1
,0
or1
depending on the ordering.See How to sort strings in JavaScript (specifically localeCompare).
So code should be: