Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Chrome incorrectly compares strings

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"]
like image 687
Alexander Avatar asked Jul 06 '26 19:07

Alexander


1 Answers

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 first

localeCompare 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.

like image 173
T.J. Crowder Avatar answered Jul 08 '26 09:07

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!