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 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"]
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);
One liner answer is localeCompare()
const ary = ["Kevin", "brandy", "Andrew"];
ary.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
console.log(ary);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With