sorted

Returns a new array or typed array with the elements sorted.

Note

This function differs from the standard Array.prototype.sort in that it:

Syntax

sorted(collection, compareFn?)

Parameters

Return value

A new collection.

If the elements of the collection are not of the same type, and the comparison function is omitted, an error is thrown.

Examples

sorted([5, 3, 100, 2, 11])
[2, 3, 5, 11, 100]
sorted(["cherry", "apricot", "banana"])
["apricot", "banana", "cherry"]
sorted(["cc", "bbb", "a"], (a, b) => a.length - b.length)
["a", "cc", "bbb"]
sorted(new Uint8Array([3, 1, 2]))
Uint8Array [1, 2, 3]
sorted([12n, 3.2m, 1])
[1, 3.2m, 12n]
sorted([1, "two"])
TypeError: expected compare function for this array type

See also