1

Say if I had a Javascript array as following and I sorted the array before printing it to console

var f = ["Salil", "Sam", "Anil", "John", "ajay", "Baba"];
f.sort();
console.log(f);

It prints as follows

Anil,Baba,John,Salil,Sameer,ajay

Why does ajay prints last, how does the case of the first letter plays a role?

thanks,

Salil

0

3 Answers 3

1

The lower-case letters come after the upper-case letters in Unicode (in the base code page at least).

You can sort so that you pay no attention to case:

f.sort(function(w1, w2) {
  w1 = w1.toLowerCase(); w2 = w2.toLowerCase();
  return w1 < w2 ? -1 : w2 < w1 ? 1 : 0;
}

More complicated collations require more complicated comparison routines. The function you pass to .sort() should take two arguments, those being two members of the array to be compared. It's pretty important that your comparator function always returns the same answer for any two strings (in either order!), or else things can get weird.

Sign up to request clarification or add additional context in comments.

Comments

1

Because lowercase letters come after uppercase letters.

To enable caseless sorting, try this:

f.sort(function(a,b) {return a.toLowerCase() < b.toLowerCase() ? -1 : 1;});

Comments

0

Here is an example in long form to make it a bit clearer with the whole if/else if/else chain for returning -1/1/0 from the sort comparison:

var caseInsensitiveComparator = function(a, b) {
  var _a = a.toLowerCase(),
      _b = b.toLowerCase();

  if (_a < _b) {
    return -1;
  } else if (_b < _a) {
    return 1;
  } else {
    return 0;
  }
};

var f = ["Salil", "Sam", "Anil", "John", "ajay", "Baba"];
f.sort(caseInsensitiveComparator);
console.log(f);
> ["ajay", "Anil", "Baba", "John", "Salil", "Sam"]

The Mozilla Developer Network page on Array.prototype.sort has an explanation on how sort works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.