Presumption was JS would be used for perlish tasks & strings were likelier in arrays than numbers. I had to pick a type!Brendan Eich
Sorts an array in place and returns a reference to the same array.
sort(compareFn?)
compareFn optional function(a, b)
Function used to determine the order of the elements. It should return a negative value if the first argument is less than the second argument, zero if they are equal, and a positive value otherwise.
If omitted, the elements are sorted as strings in ascending ASCII character order.
The original array where the elements became sorted.
When sorting numbers, you need to pass a number comparison function, such as (a, b) => a < b ? -1 : a > b ? 1 : 0, for it to work correctly.
When sorting strings that may contain Unicode characters, you need to pass your own comparison function for Unicode strings for it to work correctly.
Basically, it is not recommended to use sort() without a comparison function.
["banana", "cherry", "apple"].sort()
["apple", "banana", "cherry"]
[11,2,22,1].sort()
[1, 11, 2, 22]
[11,2,22,1].sort((a, b) => a - b)
[1, 2, 11, 22]
var original = ["c", "a", "b"]
var sorted = original.sort()
print(original)
print(sorted)
print(original === sorted)
a,b,c
a,b,c
true
// use slice() to avoid mutating the original array:
var original = ["c", "a", "b"]
var sorted = original.slice().sort()
print(original)
print(sorted)
print(original === sorted)
c,a,b
a,b,c
false