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.