Roshan
Roshan

Reputation: 2184

Custom sorting in javascript

(I have asked this question previously too here but has been marked duplicated ,but that answer doesnot meet my requirement)

I have an array a=["Apple","Mango","apple","mango"] .If I use the a.sort() the result is ["Apple", "Mango", "apple", "mango"]

But What i desire is

Apple,apple,Mango,mango

Remember It is not case inSensitive sort as whatever the order of given element in the array be ,the output should be as

Apple apple Mango mango Means the capital letter should precedes the smaller one

Upvotes: 1

Views: 97

Answers (1)

Pointy
Pointy

Reputation: 413737

Then your comparator needs to make two rounds of comparisons.

a.sort(function(e1, e2) {
  var ce1 = e1.toLowerCase(), ce2 = e2.toLowerCase();
  if (ce1 < ce2) return -1;
  if (ce1 > ce2) return 1;
  // at this point, we know that the two elements are the same
  // except for letter case ...
  if (e1 < e2) return -1;
  if (e1 > e2) return 1;
  return 0;
});

First the function checks the two elements after conversion to lower case. If they're equal after conversion to lower case, it checks the original forms. Thus "Apple" and "apple" will compare equal in the first round, and will therefore be sorted so that "Apple" comes first.

Upvotes: 8

Related Questions