Array.prototype.sort

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.

Syntax

sort(compareFn?)

Parameters

Return value

The original array where the elements became sorted.

Discussion

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.

Examples

["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