denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.97k stars 2.55k forks source link

Array sort default behavior #92

Closed tripolitov closed 3 years ago

tripolitov commented 5 years ago

I am curious if the default behaviour of array.sort method worth a WTF?

> [0,1,2,3,4,5,6,7,8,9,10].sort()
[ 0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9 ]

Explanation: According to documentation the syntax is arr.sort([compareFunction]) and compareFunction - is an optional paramter, if ommited the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

To correctly sort an array of ints valid compareFunction must be provided:

> [0,1,2,3,4,5,6,7,8,9,10].sort((a,b) => a - b)
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Pierstoval commented 5 years ago

I totally think it deserves a WTF 👍

denysdovhan commented 5 years ago

PR is welcome.

lnfnunes commented 5 years ago

If nobody is already working on it, maybe I can handle!