본문 바로가기
FRONTEND/Javascript

[Javascript] Array.sort() 정리

by LAY CODER 2021. 4. 22.

Array.prototype.sort()

 

배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환한다.

 

기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따른다.

 

유니코드 값을 따르기에 기본으로 정렬하면 다음과 같이 나온다.

 

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

 

arr.sort([compareFunction])

 

compareFunction[Optional]

 

정렬 순서를 정의하는 함수.

 

생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬된다.

 

복사본이 만들어지는 것이 아니고 원 배열이 정렬되는 것에 유의해야 한다.

 

 

compareFunction(a, b)이 0보다 작은 경우

 

a를 b보다 낮은 색인으로 정렬. 즉, a가 먼저 온다.

 

 

compareFunction(a, b)이 0보다 큰 경우

 

b를 a보다 낮은 인덱스로 소트한다.

 

 

문자열 대신 숫자를 비교하기 위해 compare 함수는 a에서 b를 뺄 수 있다.

 

이 함수는 배열을 오름차순으로 정렬한다

 

var stringArray = ['Blue', 'Humpback', 'Beluga'];
var numericStringArray = ['80', '9', '700'];
var numberArray = [40, 1, 5, 200];
var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

function compareNumbers(a, b) {
  return a - b;
}

console.log('stringArray:', stringArray.join());
console.log('Sorted:', stringArray.sort());

console.log('numberArray:', numberArray.join());
console.log('Sorted without a compare function:', numberArray.sort());
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));

console.log('numericStringArray:', numericStringArray.join());
console.log('Sorted without a compare function:', numericStringArray.sort());
console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));

console.log('mixedNumericArray:', mixedNumericArray.join());
console.log('Sorted without a compare function:', mixedNumericArray.sort());
console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));


// =================================Result=========================================


// stringArray: Blue,Humpback,Beluga
// Sorted: Beluga,Blue,Humpback

// numberArray: 40,1,5,200
// Sorted without a compare function: 1,200,40,5
// Sorted with compareNumbers: 1,5,40,200

// numericStringArray: 80,9,700
// Sorted without a compare function: 700,80,9
// Sorted with compareNumbers: 9,80,700

// mixedNumericArray: 80,9,700,40,1,5,200
// Sorted without a compare function: 1,200,40,5,700,80,9
// Sorted with compareNumbers: 1,5,9,40,80,200,700

 

 

활용

 

다음과 같이 활용하여 숫자 배열의 오름차순과 내림차순을 구할 수 있다.

 

// 오름차순

const arr = [2, 1, 3, 10];

arr.sort(function(a, b)  {
  return a - b;
});
console.log(arr); // [1, 2, 3, 10]


// 내림차순

const arr = [2, 1, 3, 10];

arr.sort(function(a, b)  {
  return b - a;
});
console.log(arr); // [10, 3, 2, 1]

 

References


 

developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

hianna.tistory.com/409

댓글