I found that using sort without comparing function would result in wrong answer and I don't know the reason.
var a = [823564440,115438165,784484492,74243042,114807987,137522503,441282327,16531729,823378840,143542612]
a.sort()
a.sort((a,b) => a-b)
The two should give same result in my mind, but they don't. And clearly the latter is correct.
a.sort()
[114807987, 115438165, 137522503, 143542612, 16531729, 441282327, 74243042, 784484492, 823378840, 823564440]
a.sort((a, b) => a-b)
[16531729, 74243042, 114807987, 115438165, 137522503, 143542612, 441282327, 784484492, 823378840, 823564440]
Can anyone tell me the reason behind this?
Per the MDN documentation:
The
sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. (Emphasis mine)†
Since you do not supply a function, default sort order is used. Thus, the elements are sorted as if they were strings, versus the latter sort, where it is sorted based on number value.
Because of this, 1
comes before 2
, 2
before 3
etc. no matter the number of digits as strings are compared place by place. (See list of unicode characters; since 1 in Unicode is U+0031, it comes before U+0032 and is thus smaller).
In your example, this would mean 115438165
coming before 74243042
although the latter is smaller mathematically. Because the strings are compared place by place, 1
is compared to 7
and is less than, thus yielding the result. For further reading, see lexicographical order.
† This is by specification. See the ECMAScript® 2015 Language Specification, Section 22.1.3.24.1 - Runtime Semantics: SortCompare( x, y )
. Here, it explains that if no sorting function is passed, string representations of x
and y
(found using ToString
) are compared.
Read the documentation.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.
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