Skip to content

toSorted() function

根据比较函数 f 返回一个排序后的新数组。与 sort 不同,此函数不会修改原始数组。

Signature:

typescript
declare function toSorted<T>(
  f: (a: T, b: T) => unknown,
  iterable: Iterable<T>,
): T[];

declare function toSorted<T>(
  f: (a: T, b: T) => unknown,
  iterable: AsyncIterable<T>,
): Promise<T[]>;

declare function toSorted<T extends Iterable<unknown> | AsyncIterable<unknown>>(
  f: (a: IterableInfer<T>, b: IterableInfer<T>) => unknown,
): (iterable: T) => ReturnValueType<T, IterableInfer<T>[]>;

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] - 原始数组不会被修改

toSorted((a, b) => a.localeCompare(b), "bcdaef"); // ["a", "b", "c", "d", "e", "f"]

// 可以在管道中使用
pipe(
  [3, 4, 1, 2, 5, 2],
  filter((a) => a % 2 !== 0),
  toSorted((a, b) => a > b),
); // [1, 3, 5]

Open Source Code

Released under the Apache-2.0 License.