-1

I am trying to figure out how to sort my array by objects in that array. In this example I want to be be able to sort my array by player name, or by player score.

var topPlayers = new Array();

$(".player").each( function(i) {
    topPlayers[i] = {};
    topPlayers[i]["name"] = $(this).children(".name").text();
    topPlayers[i]["score"] = $(this).children(".score").text();
});


topPlayers.sort(function(a.name,b.name){return a.name-b.name}); //This is the line of code I can't figure...
  • 1
    possible duplicate of [How to sort an array of javascript objects?](http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects) and [How to sort an array of objects with jquery or javascript](http://stackoverflow.com/questions/5503900/how-to-sort-an-array-of-objects-with-jquery-or-javascript). – Felix Kling Nov 12 '12 at 00:22
  • Btw, subtracting two strings does not make a lot of sense... what do you expect `'foo' - 'bar'` to be? If you have seen this in other implementations, then that's because both values have been expected to be numbers. In that case it is more concise to use subtraction than comparison. – Felix Kling Nov 12 '12 at 01:02

2 Answers2

1

Sorting by name:

topPlayers.sort(function(a, b)
{ 
  if ( a.name > b.name ) return 1;
  else if ( a.name < b.name ) return -1;
  else return 0;
}); 

Sorting by score:

topPlayers.sort(function(a, b)
{ 
  return a.score - b.score;
}); 
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
0

The sort method takes a function that makes a comparison and returns a number depending on the result:

topPlayers.sort(function(a,b){
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
});

For numeric values you can just subtract them to get the right return value:

topPlayers.sort(function(a,b){
  return a.score - b.score;
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    You shouldn't be using `>`/`<` operators on characters this doesn't work on Safari, IOS devices. Haven't testet on other mobile devices. Instead use: `a.name.charCodeAt(0)-b.name.charCodeAt(0)` – Andreas Louv Nov 12 '12 at 00:59
  • @NULL: That's not sufficient. Why is no one mentioning `strA.localeCompare(strB)`? – Felix Kling Nov 12 '12 at 01:01
  • 1
    @FelixKling So if you know that all along why didn't you post it in the first place? – Andreas Louv Nov 12 '12 at 01:03
  • @NULL: You mean as an answer? Because this question is a duplicate. If you mean as comment to this answer, I did not look that closely at it, because, again, it's a duplicate. – Felix Kling Nov 12 '12 at 01:05
  • @NULL: Do you have any reference to string comparison being broken on Safari IOS? I can't find anything about it. Comparing the first character of the string doesn't do the same thing, so that won't suffice. – Guffa Nov 12 '12 at 01:10