728x90

✨ 문자 또는 숫자를 순서대로 정렬할 때 사용하는 helper method

(e.g., strArr.sort() or numArr.sort((a, b) => a - b)) 문자를 sort 할 때, 10이 넘어가는 숫자를 sort할 때, 왼쪽처럼 사용법이 다르다.
Numbers는 Strings으로 변환되기 때문에, Unicode order에 따라 80이 9보다 앞에 위치한다.

💻Example Code

const strArr = [ 'c', 'b', 'a' ];
const numArr = [ 3, 33, 2, 22, 1, 11 ];

console.log( strArr.sort() );
console.log( numArr.sort() ); // For Example
console.log( numArr.sort((a,b) => a - b) );

실행 결과( 2번째 결과는 Number를 그냥 sort() 했을 때 결과이다)

😋 Anagrams(철자 순서를 바꾼 말) Algorithm에서 유용하게 사용 가능하며, 다양한 상황에서 사용 가능하다.

✔ sort((a, b) => a - b)로 숫자가 정렬되는 것을 Test 해보자

const numArr = [ 3, 2, 1, 11, 22 ,33 ];

function compare(a, b) {
console.log('a:'+a);
console.log('b:'+b);
return a - b; }

a가 b보다 작아서 negative가 나오는 경우 a는 b보다 낮은 숫자의 index를 갖고, 0은 변화 없음, 0보다 크면 a는 b보다 높은 index를 갖게 되는 식으로 정렬된다. 아마 선택 정렬(Selection Sort)과 비슷한 방식이 아닐까 생각해본다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 

Array.prototype.sort()

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

developer.mozilla.org

 

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

String.prototype.replace()  (0) 2019.12.29
Object.keys() & Object.values()  (0) 2019.12.29
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.includes()  (0) 2019.12.26
Array.prototype.every()  (0) 2019.12.24

+ Recent posts