1

(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

Community
  • 1
  • 1
Roshan
  • 2,144
  • 2
  • 16
  • 28
  • The answer does meet your requirement...["Apple","Mango","apple","mango"].sort(function (a, b) { return a.toLowerCase().localeCompare(b.toLowerCase()); }); returns ["Apple", "apple", "Mango", "mango"] – Steve Clanton Aug 19 '14 at 12:26
  • So you need to add an additional check inside if the strings are equal and do another check. – epascarello Aug 19 '14 at 12:26
  • 1
    Pointy's answer is great. In case you are basically not yet familiar with the function as parameter for sort, look here: [http://www.javascripture.com/Array#sort_Function](http://www.javascripture.com/Array#sort_Function) – peter_the_oak Aug 19 '14 at 12:27
  • @peter_the_oak ,thanks for the link, it isreally helpfull – Roshan Aug 19 '14 at 12:29
  • possible duplicate of [Custom sorting on array in javascript](http://stackoverflow.com/questions/25382615/custom-sorting-on-array-in-javascript) – cracker Aug 19 '14 at 12:33

1 Answers1

8

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614