javascript-sort

Javascript Array sort

기본

오름차순

1
2
3
const array = ['z', 'c', 'a'];
array.sort();
console.log(array);

image

내림차순

1
2
3
const array = ['z', 'c', 'a'];
array.sort().reverse();
console.log(array);

image

Number type

문제

1
2
3
4
const points = [1, 2, 10, 20, 100, 30];

points.sort();
console.log(points);

image

.sort() 메소드는 배열요소를 문자로 인식
문자로 ‘10’이 ‘2’보다 작기 때문에 오름차순으로 10이 2보다 앞에 위치하게 됨

숫자배열의 sort

1
2
points.sort((a, b) => { return a - b; });
console.log(points);

(a, b) => { return a-b } 함수를 .sort() 메소드 매개변수로 전달하여 숫자 타입의 배열을 오름차순으로 정렬 할 수 있음

image

(a, b) => { return a-b }(a, b) => { return b-a }로 변경하여 내림차순 구현 가능

Object 배열 sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const javascript = [
{ id: 3, value: 'Vue.js' },
{ id: 1, value: 'vanilla' },
{ id: 2, value: 'Nodejs' }
];

// 비교 함수
function compare(key) {
return function (a, b) {
return a[key] > b[key] ? 1 : (a[key] < b[key] ? -1 : 0);
};
}

// id를 기준으로 정렬
javascript.sort(compare('id'));
console.log(javascript);

// value 기준으로 정렬
javascript.sort(compare('value'));
console.log(javascript);

프로퍼티 값이 문자열인 경우, - 산술 연산으로 비교하면 NaN이 발생

비교 연산을 이용

image

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×