Javascript Array.prototype.sort () is wrong without comparing a function

I found that using sorting without comparing a function would lead to a 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)

Both should give me the same result, but they do not. And, of course, the latter is true.

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 someone tell me the reason for this?

+4
source share
2 answers

In the MDN Documentation :

The method sort()sorts the elements of the array in place and returns an array. The variety is not necessarily stable. The default sort order corresponds to Unicode string codes. (Emphasis mine) †

, . , , , , .

- 1 2, 2 3 .., , . (. , 1 - U + 0031, U + 0032 , , ).

115438165, 74243042, . , 1 7 , . . .


† . . ECMAScript® 2015 , 22.1.3.24.1 - : SortCompare( x, y ). , , x y ( ToString) .

+5

.

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

compareFunction , Unicode. , "" "". 9 80, , "80" "9" Unicode.

+3

Source: https://habr.com/ru/post/1663477/


All Articles