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:
Why does this happen in JavaScript?
How can I sort the strings array
["Kevin", "brandy", "Andrew"]
according to the dictionary ordering of words usingsort()
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"]