array.sort() does not work in IE 11 with compareFunction

Mario Levrero picture Mario Levrero · Nov 25, 2014 · Viewed 16.6k times · Source

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!

Answer

Kos picture Kos · Nov 25, 2014

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>");
  }
}