views:

11319

answers:

2

I have a list of data objects to sort. I want to do something like

list.sort(function(item1, item2){
    return item1.attr - item2.attr;
}) 

to sort it based on a string attribute of the object. But I found that the minus (-) operator does not work for strings in JavaScript. So how do you do string comparison?

+10  A: 

Well, this ought to work:

if ( item1.attr < item2.attr )
  return -1;
if ( item1.attr > item2.attr )
  return 1;
return 0;

[Edit: uh, and I guess you could also use localeCompare():

return item1.attr.localeCompare(item2.attr);

I did not previously know about it. Heh, cool, learned something. ]

Shog9
thank you, I also learned about the localeCompare ;).
Nordes
A: 

Sorry, stupid question. You should use > or < and == here. So the solution would be:

list.sort(function(item1, item2){
    var val1 = item1.attr;
    var val2 = item2.attr;
    if (val1 == val2)
        return 0;
    if (val1 > val2)
        return 1;
    if (val1 < val2)
        return -1;
});
toby
-1 for unformatted, incomplete code.
Sean McMillan
Sorry, stupid attitude.
Eran Betzalel