Skip to Content

sort

sort() 함수는 배열의 요소를 정렬한 후 그 배열을 반환한다.
원본 배열이 직접 변경된다.



sort 형식

arr.sort((a, b) => { return 비교값 });
  • a: 비교 대상 앞 요소
  • b: 비교 대상 뒤 요소
  • 반환값이 음수면 a를 b 앞에 정렬한다
  • 반환값이 양수면 b를 a 앞에 정렬한다
  • 반환값이 0이면 순서를 유지한다


숫자 정렬

비교 함수 없이 sort()를 사용하면 요소를 문자열로 변환해서 정렬하기 때문에 숫자 배열에서 의도치 않은 결과가 나온다.

const arr = [10, 9, 2, 1, 100]; // 비교 함수 없이 사용하면 문자열 기준으로 정렬된다 console.log(arr.sort()) // [1, 10, 100, 2, 9]; // 오름차순 console.log(arr.sort((a, b) => a - b)); // [1, 2, 9, 10, 100] //내림차순 console.log(arr.sort((a, b) => b - a)); // [100, 10, 9, 2, 1]


문자열 정렬

const fruits = ['banana', 'apple', 'cherry', 'melon']; // 오름차순 (알파벳 순) console.log(fruits.sort()); // ['apple', 'banana', 'cherry', 'melon']


객체 배열 정렬

const users = [ { id: 1, name: 'gori', age: 28 }, { id: 2, name: 'gildong', age: 17 }, { id: 3, name: 'chunhyang', age: 16 }, ]; // 나이 기준 오름차순 정렬 users.sort((a, b) => a.age - b.age); console.log(users); // [{ id: 3, name: 'chunhyang', age: 16 }, { id: 2, name: 'gildong', age: 17 }, { id: 1, name: 'gori', age: 28 }]


원본 배열 보존

sort()는 원본 배열을 변경하기 때문에 원본을 유지하려면 복사 후 정렬해야 한다.

const arr = [3, 1, 2]; // 스프레드 연산자로 복사 후 정렬한다 const sorted = [...arr].sort((a, b) => a - b); console.log(arr); // [3, 1, 2] (원본 유지) console.log(sorted); // [1, 2, 3]


마지막 수정