웹 개발

배열 정렬 하기 - toSorted(), Sort()

Blue_bull 2025. 2. 15. 11:06

toSorted() 메서드 (JavaScript)


📌 toSorted()란?

toSorted()배열을 정렬할 때 원본 배열을 변경하지 않고 새로운 정렬된 배열을 반환하는 메서드이다.
즉, 불변성(immutability)을 유지하면서 정렬이 가능하다.

ES2023(ES14)부터 도입된 최신 메서드
원본 배열을 변경하지 않고 새로운 정렬된 배열을 반환
콜백 함수를 이용해 원하는 방식으로 정렬 가능


📌 toSorted() 기본 사용법

const numbers = [3, 1, 4, 1, 5, 9];

const sortedNumbers = numbers.toSorted();

console.log(sortedNumbers); // [1, 1, 3, 4, 5, 9]
console.log(numbers); // [3, 1, 4, 1, 5, 9] (원본 배열 변경 없음)

오름차순(기본 정렬)으로 새로운 배열을 반환
원본 배열(numbers)은 변경되지 않음


📌 toSorted() 정렬 방식 지정

toSorted()콜백 함수를 사용하여 정렬 기준을 지정할 수 있다.
sort()와 동일한 방식으로 비교 함수(compare function)를 사용할 수 있다.

const numbers = [3, 1, 4, 1, 5, 9];

// 오름차순 정렬
const ascending = numbers.toSorted((a, b) => a - b);
console.log(ascending); // [1, 1, 3, 4, 5, 9]

// 내림차순 정렬
const descending = numbers.toSorted((a, b) => b - a);
console.log(descending); // [9, 5, 4, 3, 1, 1]

a - b오름차순 정렬
b - a내림차순 정렬


📌 toSorted() vs sort()

메서드 원본 변경 여부 반환 값
sort() ✅ 원본 배열 변경됨 원본 배열을 정렬한 값
toSorted() ❌ 원본 배열 변경 없음 새로운 정렬된 배열 반환
const arr = [3, 2, 1];

// sort()는 원본 배열을 변경
arr.sort();
console.log(arr); // [1, 2, 3] (원본 배열 변경됨)

// toSorted()는 원본 배열을 변경하지 않음
const sortedArr = arr.toSorted();
console.log(sortedArr); // [1, 2, 3] (새로운 배열 반환)
console.log(arr); // [3, 2, 1] (원본 배열 유지)

sort()는 원본 배열을 변경하므로 조심해야 함
toSorted()불변성을 유지하며 정렬된 새로운 배열을 반환


📌 문자열 배열 정렬

const fruits = ["banana", "apple", "cherry"];

// 알파벳순 정렬 (기본)
const sortedFruits = fruits.toSorted();
console.log(sortedFruits); // ['apple', 'banana', 'cherry']

// 내림차순 정렬
const descFruits = fruits.toSorted((a, b) => b.localeCompare(a));
console.log(descFruits); // ['cherry', 'banana', 'apple']

✅ 기본적으로 알파벳순 정렬
localeCompare()를 사용하여 내림차순 정렬 가능


📌 객체 배열 정렬

객체 배열에서 특정 속성 값을 기준으로 정렬할 수도 있다.

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 22 }
];

// 나이(age) 기준 오름차순 정렬
const sortedByAge = users.toSorted((a, b) => a.age - b.age);
console.log(sortedByAge);
/*
[
  { name: "Charlie", age: 22 },
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
]
*/

✅ 객체 배열에서도 toSorted()를 활용하여 특정 속성 값을 기준으로 정렬 가능


📌 toSorted()가 지원되지 않는 경우 해결 방법

toSorted()최신 ES2023(ES14) 기능이므로, 구버전 브라우저에서는 지원되지 않을 수 있다.
이 경우 slice().sort()로 같은 기능을 구현할 수 있다.

const numbers = [3, 1, 4, 1, 5, 9];

// toSorted()가 지원되지 않는 환경에서는 slice() + sort() 사용
const sortedNumbers = numbers.slice().sort((a, b) => a - b);

console.log(sortedNumbers); // [1, 1, 3, 4, 5, 9]
console.log(numbers); // [3, 1, 4, 1, 5, 9] (원본 유지)

slice()를 사용하여 원본 배열을 복사한 후 sort() 적용
toSorted()와 동일한 동작을 구현 가능


🔥 toSorted() 핵심 요약

1️⃣ ES2023부터 지원되는 새로운 메서드
2️⃣ 원본 배열을 변경하지 않고 새로운 정렬된 배열을 반환
3️⃣ 비교 함수를 이용해 오름차순/내림차순 정렬 가능
4️⃣ 객체 배열도 특정 속성을 기준으로 정렬 가능
5️⃣ 구버전 브라우저에서는 slice().sort()로 대체 가능

불변성을 유지하면서 정렬이 필요한 경우 toSorted()를 사용 🚀