8

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"]
2
  • 1
    This question has several answers already, one candidate here stackoverflow.com/questions/8996963/… Commented Jan 18, 2019 at 7:42
  • 1
    For your point 1 type "a" > "B" in the console. or "a".codePointAt(0) & "B".codePointAt(0) Commented Jan 18, 2019 at 7:43

3 Answers 3

14

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);

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

Comments

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);

Comments

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);

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.