Returns a new array or typed array with the elements sorted.
This function differs from the standard Array.prototype.sort in that it:
sorted(collection, compareFn?)
collection
An array or a typed array to sort. The collection must be homogeneous, that is all elements of the collection must be of the same type (a mix of "number", "bigint", "bigfloat", and “bigdecial” is allowed).
compareFn?
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 numeric collection is sorted in ascending order, the string collection is sorted using the canonical Unicode representation, the date collection is sorted chronologically.
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.
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