1

Given the following:

var array = [{"name":"zoe", "hotdogs":5},{"name":"april", "hotdogs":5},{"name":"ryan", "hot dogs":8}]

How can I sort the elements of the array by name using JavaScript?

var array = [{"name":"april", "hotdogs":5},{"name":"ryan", "hotdogs":8},{"name":"zoe", "hotdogs":5}]

Is there a way to apply some function to sort the objects? Are there helper libraries that help with performance?

I tried the following:

array.sort(function(a, b) {
    return a.name > b.name
});

But it appeared to have no effect on the resulting array when I try to print it out whatsoever.

Borodin
  • 126,100
  • 9
  • 70
  • 144
Setsuna
  • 2,081
  • 7
  • 32
  • 50
  • 2
    Try `return (a.name>b.name)-(b.name>a.name)`. `.sort` interprets `0` (AKA `+false`) as "equals" – John Dvorak Mar 03 '13 at 17:30
  • @JanDvorak is correct http://jsfiddle.net/avWXu/ – C.. Mar 03 '13 at 17:33
  • Sorry but I don't see how this is a duplicate of the other. The other's accepted answer shows using `parseFloat`. No details are given that the sort function must return -1, 0, 1 so the answers on the other question are basically irrelevant to this one. – gman Nov 23 '16 at 08:20

2 Answers2

1

Use .localeCompare().

array.sort(function(a, b) {
    return a.name.localeCompare(b.name)
});
the system
  • 9,244
  • 40
  • 46
  • This is horrible answer. From the docs you linked to: *the locale and sort order used are entirely implementation dependent*. Great. So I get one sort on the server, and different sort on every user's machine. No thanks – gman Nov 23 '16 at 08:23
0

The function should return integer, like C strcmp, so do:

if a.name > b.name {
  return 1;
} else if ( a.name == b.name) {
  return 0;
}
return -1
eran
  • 6,731
  • 6
  • 35
  • 52