Can anybody explain is it a bug in Chrome or I incorrectly compare strings?
Sort method in Chrome provides odd (at least for me) result. I do the following:
var a = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"]
a.sort((i1,i2)=>i1>i2)
["7", "c", "b", "a", "9", "8", "6", "5", "4", "3", "2", "1"]
Firefox gives expected result:
["c", "b", "a", "9", "8", "7", "6", "5", "4", "3","2","1"]
It's a bug in your sort callback, not the JavaScript engine.
The callback must return a number, not a boolean:
0 if the arguments are equivalent<0 if the first argument is "less than" the second>0 if the second argument is "less than" the firstlocaleCompare is handy for getting a correct return value if you want the array in ascending order by string comparison in the natural ordering. In your case, though, you want the opposite, so negate it:
var a = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c"]
a.sort((i1, i2) => -i1.localeCompare(i2));
console.log(a);
...or (doh) just do i2.localeCompare(i1) instead.
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