반응형
지난 번에 filter 함수를 봤는데
우리는 비슷한 sort와 map 함수도 살펴볼 수 있다
개인적으로는 filter map이 상당히 유사하다고 느껴진다
map() 함수는 기존에 사용해봐서 어렵지 않다
map 안에 있는 요소들을 하나 씩 꺼내서 반복문처럼 돌리는 것
const numbers = [1, 2, 3];
const double = numbers.map((e)=>e*2);
// 출력 [2, 4, 6]
sort 함수도 정리해볼까 한다
Sort()
sort 함수에서는 String 배열일 때
그냥 abc 순서대로 배열을 한다
(배열 자체가 변경된다)
근데 숫자일 때?
숫자의 크기를 비교하는 것이 아니라 1,2,3,4, 그 앞 숫자의 크기를 비교하게 된다
그래서 아래를 보면 10,000이 제일 끝이 아니라 숫자 1 뒤로 위치하게 된 것
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]
그럼 숫자 크기대로 하려면 어떻게 해야 할까?
아래처럼
(a,b) => { return a - b };
코드를 sort 함수 내부에 추가해주면 된다
값들을 비교해서 크고 작은 순서대로 배열에서 정렬되도록 한다
Array.prototype.sort() - JavaScript | MDN
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units val
developer.mozilla.org
반응형
'온라인 강의 > React 완벽 가이드 [Udemy]' 카테고리의 다른 글
22. 차세대 JavaScript - 요약 (0) | 2023.05.31 |
---|---|
21. 마무리 (0) | 2023.05.31 |
19. 참조형 및 원시형 데이터 타입 (0) | 2023.05.31 |
18. 구조분해할당(Destructuring) (0) | 2023.05.31 |
17. 스프레드 및 나머지 연산자 (0) | 2023.05.31 |