airportyh airportyh - 1 month ago 7
Javascript Question

How do you do string comparison in JavaScript?

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?

Answer

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. ]

Comments