[javascript] comparing 2 strings alphabetically for sorting purposes

I'm trying to compare 2 strings alphabetically for sorting purposes. For example I want to have a boolean check like if('aaaa' < 'ab'). I tried it, but it's not giving me correct results, so I guess that's not the right syntax. How do I do this in jquery or Javascript?

This question is related to javascript jquery

The answer is


Lets say that we have an array of objects:

{ name : String }

then we can sort our array as follows:

array.sort(function(a, b) {
    var orderBool = a.name > b.name;
    return orderBool ? 1 : -1;
});

Note: Be careful for upper letters, you may need to cast your string to lower case due to your purpose.


Just remember that string comparison like "x" > "X" is case-sensitive

"aa" < "ab" //true
"aa" < "Ab" //false

You can use .toLowerCase() to compare without case sensitivity.


You do say that the comparison is for sorting purposes. Then I suggest instead:

"a".localeCompare("b");

It returns -1 since "a" < "b", 1 or 0 otherwise, like you need for Array.prototype.sort()

Keep in mind that sorting is locale dependent. E.g. in German, ä is a variant of a, so "ä".localeCompare("b", "de-DE") returns -1. In Swedish, ä is one of the last letters in the alphabet, so "ä".localeCompare("b", "se-SE") returns 1.

Without the second parameter to localeCompare, the browser's locale is used. Which in my experience is never what I want, because then it'll sort differently than the server, which has a fixed locale for all users.


"a".localeCompare("b") should actually return -1 since a sorts before b

http://www.w3schools.com/jsref/jsref_localecompare.asp