Array.sort () doesn't work in IE 11 with compareFunction
I am sorting an array following JavaScript Sort Method (). When I use the parameter compareFunction
, Internet Explorer 11 doesn't sort correctly.
I have a command array with players. These players have names:
var team = [
{name:"Waldo"},
{name:"Sarah"}
];
But I want to show them in alphabetical sorting of the stadium video card. So I have a list to add 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>" );
}
}
The problem is that some clubs use Internet Explorer 11 in their stadiums, and the sort () function when I use my own compareFunction
doesn't work as expected in IE11, so Waldo shows up first than Sarah and fans get confused.
I created Plunker where you can reproduce it:
- Firefox 33.1 - Work! :)
- Chrome 39.0.2171.65 - Working !! :)
- Internet Explorer 11.0.9600 - not working :(
Any idea to allow sort () for each browser?
Thank!
source to share
Your mapper doesn't look correct:
function(a, b){return a.name > b.name;}
Returns true
either false
, while depending on the order it should return -1
, 0
or 1
.
See How do you perform string comparison in JavaScript? (in particular localeCompare ).
So the 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(var i=0; i < team.length; i++){
$("#myTeamAfter").append( "<li>" + team[i].name + "</li>" );
}
}
source to share