Array.prototype.toSorted()

Baseline 2023

Newly available

Since July 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

ArraytoSorted() 메서드는 sort()에 대응되는 복사 메서드입니다. 이 메서드는 요소들을 오름차순으로 정렬한 새로운 배열을 반환합니다.

구문

js
// 함수 없이 사용
toSorted()

// 화살표 함수
toSorted((a, b) => { /* … */ })

// 비교 함수
toSorted(compareFn)

// 인라인 비교 함수
toSorted(function compareFn(a, b) { /* … */ })

매개변수

compareFn Optional

정렬 순서를 정의하는 함수를 지정합니다. 생략하면 배열 요소는 문자열로 변환되고 각 문자의 유니코드 포인트 값에 따라 정렬됩니다.

a

비교할 첫 번째 요소입니다.

b

비교할 두 번째 요소입니다.

반환 값

요소들을 오름차순으로 정렬한 새로운 배열입니다.

설명

compareFn 매개변수에 대해 더 알아보려면 sort()를 참조하세요.

희소 배열에서 toSorted() 메서드는 빈 슬롯을 undefined 값으로 간주하고 반복합니다.

toSorted() 메서드는 일반화되어 있습니다. this 값이 length 속성과 정수 키 속성을 가지고 있다고 가정합니다.

예제

배열 정렬하기

js
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]

더 많은 사용 예제는 sort()를 참조하세요.

희소 배열에서 toSorted() 사용하기

빈 슬롯은 undefined 값으로 간주되어 정렬됩니다. 빈 슬롯은 항상 배열의 끝으로 정렬되며 compareFn은 호출되지 않습니다.

js
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]

배열이 아닌 객체에서 toSorted() 호출하기

toSorted() 메서드는 thislength 속성을 읽습니다. 그런 다음 0부터 length - 1까지의 범위에 있는 모든 정수 키 속성을 수집하여 정렬하고 새 배열에 씁니다.

js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
};
console.log(Array.prototype.toSorted.call(arrayLike));
// [4, 5, undefined]

명세서

Specification
ECMAScript Language Specification
# sec-array.prototype.tosorted

브라우저 호환성

BCD tables only load in the browser

같이 보기