6

I have the following JavaScript code:

   const ary = ["Kevin", "brandy", "Andrew"];
   const nary = ary.sort();
   console.log(nary);

I expected the output of the above code to be ["Andrew","brandy", "Kevin"] i.e according to the dictionary ordering of words.

But in the console I get the output:

    ["Andrew","Kevin","brandy"]

When I switched the b in "brandy" to uppercase B, and ran the code again,

     const ary = ["Kevin", "Brandy", "Andrew"];
     const nary = ary.sort();
     console.log(nary);

the output came as expected:

["Andrew","Brandy","Kevin"]

i.e according to the dictionary ordering of words.

That means the sorting priority is given to words whose starting letter is uppercase, and then words with lowercase starting letter are sorted.

My questions are:

  1. Why does this happen in JavaScript?

  2. How can I sort the strings array ["Kevin", "brandy", "Andrew"] according to the dictionary ordering of words using sort() function?

Input code:

   const ary = ["Kevin", "brandy", "Andrew"];
   const nary = ary.sort();
   console.log(nary);   

Console Output: 
   ["Andrew","Kevin","brandy"]

I want the Output as:

   ["Andrew","brandy", "Kevin"]
Keith M
  • 421
  • 1
  • 8
  • 18
  • 1
    This question has several answers already, one candidate here https://stackoverflow.com/questions/8996963/how-to-perform-case-insensitive-sorting-in-javascript – visibleman Jan 18 '19 at 07:42
  • 1
    For your point 1 type `"a" > "B"` in the console. or `"a".codePointAt(0)` & `"B".codePointAt(0)` – Kaiido Jan 18 '19 at 07:43

3 Answers3

13

It is because when there is no callback function supplied the elements are sorted after converted to UTF-16 code units. In your case it may be the reason that the utf converted string for Kelvin is before brandy so it is sorting in that order.

Use localeCompare

const ary = ["Kevin", "brandy", "Andrew"];
const nary = ary.sort(function(a, b) {
  return a.localeCompare(b)

});
console.log(nary);
brk
  • 48,835
  • 10
  • 56
  • 78
5

One liner answer is localeCompare()

const ary = ["Kevin", "brandy", "Andrew"];
ary.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});
console.log(ary);
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
3

Just convert the keys to lowerCase first so that the keys become case Insensitive. And the reason why this happens is because of the way Javascript compares ie.['a'< 'A'], you can use Local compare. To compare based on browser settings.

let arr = ["Andrew","brandy", "Kevin"];
let sorted = arr.sort((a,b) => {
 a.toLowerCase() > b.toLowerCase();
})
console.log(sorted);
Black Mamba
  • 13,632
  • 6
  • 82
  • 105