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]