toSorted() function
Returns a new array, sorted according to the comparator f, which should accept two values. Unlike sort, this function does not mutate the original array.
Signature:
typescript
declare function toSorted(f: (a: any, b: any) => unknown, iterable: readonly []): any[];Example
ts
const arr = [3, 4, 1, 2, 5, 2];
toSorted((a, b) => a > b, arr); // [1, 2, 2, 3, 4, 5]
arr; // [3, 4, 1, 2, 5, 2] - original array is unchanged
toSorted((a, b) => a.localeCompare(b), "bcdaef"); // ["a", "b", "c", "d", "e", "f"]
// Can be used in a pipeline
pipe(
[3, 4, 1, 2, 5, 2],
filter((a) => a % 2 !== 0),
toSorted((a, b) => a > b),
); // [1, 3, 5]