Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

자바스크립트에서 배열을 정렬하는 방법, 예제로 쉽게 배우기

정렬(Sorting)이란?

정렬이란 배열의 요소들을 오름차순 또는 내림차순으로 나열하는 것을 의미합니다. 자바스크립트에서는 Array.sort() 메서드를 사용하여 배열을 정렬할 수 있으며, 이 메서드는 비교 함수(compare function)가 반환하는 값에 따라 요소들의 순서를 결정합니다.

비교 함수는 두 개의 인수(a, b)를 받아 다음과 같이 동작합니다.
- 반환값이 음수이면 → a가 b보다 앞에 위치합니다.
- 반환값이 양수이면 → b가 a보다 앞에 위치합니다.
- 반환값이 0이면 → 두 요소의 순서가 변경되지 않습니다.

a) age 속성을 기준으로 내림차순 정렬하기

아래 예제에서는 각 사람의 수명(death - birthdate)을 계산한 뒤, 그 값을 기준으로 배열을 내림차순으로 정렬합니다. 비교 결과가 클 때 -1을 반환하므로 수명이 긴 사람이 앞쪽에 배치됩니다.

예제

<html>
<body>
<script>
    var persons = [
                     { name: 'rajesh', birthdate: 1845, death: 1875 },
                     { name: 'Bharat', birthdate: 1909, death: 1917},
                     { name: 'baba', birthdate: 1950, death: 1972 },
                     { name: 'Tanish', birthdate: 2039, death: 2067 },
                     { name: 'rahim', birthdate: 1989, death: 2049 }
                 ]
    var sortedArray = persons.sort(function(a,b) {
    var lastPerson = a.death - a.birthdate;
    var nextPerson = b.death - b.birthdate;
    if (lastPerson > nextPerson) {
    return -1;
    } else {
    return 1;
    }
    });
    console.log(sortedArray);
</script>
</body>
</html>

브라우저 콘솔 출력 결과

{name: "rahim", birthdate: 1989, death: 2049}
{name: "rajesh", birthdate: 1845, death: 1875}
{name: "Tanish", birthdate: 2039, death: 2067}
{name: "baba", birthdate: 1950, death: 1972}
{name: "Bharat", birthdate: 1909, death: 1917}

b) age 속성을 기준으로 오름차순 정렬하기

같은 데이터를 오름차순으로 정렬하려면 비교 조건만 반대로 바꾸면 됩니다. 아래 예제에서는 lastPerson이 nextPerson보다 작을 때 -1을 반환하므로, 수명이 짧은 사람부터 차례대로 정렬됩니다.

예제

<html>
<body>
<script>
    var persons = [
                    { name: 'rajesh', birthdate: 1845, death: 1875 },
                    { name: 'Bharat', birthdate: 1909, death: 1917},
                    { name: 'baba', birthdate: 1950, death: 1972 },
                    { name: 'Tanish', birthdate: 2039, death: 2067 },
                    { name: 'rahim', birthdate: 1989, death: 2049 }
                 ]
    var sortedArray = persons.sort(function(a,b) {
    var lastPerson = a.death - a.birthdate;
    var nextPerson = b.death - b.birthdate;
    if (lastPerson < nextPerson) {
    return -1;
    } else
    {
    return 1;
    }
    });
    console.log(sortedArray);  
</script>
</body>
</html>

브라우저 콘솔 출력 결과

{name: "Bharat", birthdate: 1909, death: 1917}
{name: "baba", birthdate: 1950, death: 1972}
{name: "Tanish", birthdate: 2039, death: 2067}
{name: "rajesh", birthdate: 1845, death: 1875}
{name: "rahim", birthdate: 1989, death: 2049}

이처럼 sort() 메서드에 비교 함수를 직접 작성하면 단순 문자열이나 숫자뿐만 아니라 객체 배열도 원하는 기준에 따라 자유롭게 정렬할 수 있습니다.