Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Javascript's native sort method work?

[1, false, 10, "b", 3, "33", ":", "R", "^"].sort()

Yields the following sort:

[1, 10, 3, "33", ":", "R", "^", "b", false]

Can anyone explain how the sort method works? I'm guessing that it must be translating everything into ASCII.

The plot thickens when I do this

[1, false, 10, "b", 3, "33", ":", "R", "^"].sort(function(a,b) {return b-a})

Outputs the following:

[10, 1, false, "b", "33", 3, ":", "R", "^"]

Any method to this madness?

like image 441
Anthony Chung Avatar asked Apr 10 '26 07:04

Anthony Chung


1 Answers

From MDN:

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order.

And:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

like image 130
TbWill4321 Avatar answered Apr 12 '26 20:04

TbWill4321



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!