Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array sort() does not sort array of strings correctly [duplicate]

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"]
like image 411
Keith M Avatar asked Jan 18 '19 07:01

Keith M


3 Answers

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);
like image 192
brk Avatar answered Sep 27 '22 22:09

brk


One liner answer is localeCompare()

const ary = ["Kevin", "brandy", "Andrew"];
ary.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});
console.log(ary);
like image 45
Sudhir Ojha Avatar answered Sep 27 '22 22:09

Sudhir Ojha


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);
like image 44
Black Mamba Avatar answered Sep 27 '22 20:09

Black Mamba