Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

죽이죽이

JS : 데이터 정렬 본문

Javascript

JS : 데이터 정렬

죽이죽이 2024. 2. 16. 13:08

데이터 정렬 방법

※ Number
- string 타입으로 변환 후 비교를 한다.

// 숫자가 10 미만일때는 정상적으로 정렬이 된다.
const numberList1 = [5, 7, 2, 4];
console.log(numberList1.sort()); // [2, 4, 5, 7]

// 숫자가 10이 넘어가면서부터 원하는 방향과 다르게 정렬이 된다.
const numberList2 = [5, 10, 1, 7];
console.log(numberList2.sort()); // [1, 10, 5, 7]

// sort 함수 내부에서 비교함수를 사용해서 비교할 경우 정상적으로 정렬이 된다.
// 비교함수에서 a값은 앞에 값, b값은 뒤에 값을 가리킨다.
console.log(numberList2.sort((a, b) => a - b)); // [1, 5, 7, 10]

// 오름차순 정렬
console.log(numberList2.sort((a, b) => b - a)); // [10, 7, 5, 1]


※ String
- ASCII 코드로 변환 후 비교한다.
const stringList = ['a', 'c', 'A', 'C'];

// sort만 사용할 경우 ASCII 코드 비교로 인해 원하는 방향과 다르게 정렬이 된다.
console.log(stringList.sort()); // ['A', 'C', 'a', 'c']

// localeCompare 사용 시 사전 순과 동일하게 정렬된다.
console.log(stringList.sort((a, b) => a.localeCompare(b))); // ['a', 'A', 'c', 'C']



※ Object
- 내부 속성에 직접 접근해서 비교할 수 있다.
const objList = [
    {weight: 10, cost: 10, name: "양파"},
    {weight: 5, cost: 20, name: "토마토"},
    {weight: 20, cost: 5, name: "당근"},
];

// [
//   { weight: 5, cost: 20, name: '토마토' },
//   { weight: 10, cost: 10, name: '양파' },
//   { weight: 20, cost: 5, name: '당근' }
// ]
console.log(objList.sort((a, b) => a.weight - b.weight)); // weight 기준 오름차순

// [
//   { weight: 20, cost: 5, name: '당근' },
//   { weight: 10, cost: 10, name: '양파' },
//   { weight: 5, cost: 20, name: '토마토' }
// ]
console.log(objList.sort((a, b) => b.weight - a.weight)); // weight 기준 내림차순

// [
//   { weight: 20, cost: 5, name: '당근' },
//   { weight: 10, cost: 10, name: '양파' },
//   { weight: 5, cost: 20, name: '토마토' }
// ]
console.log(objList.sort((a, b) => a.cost - b.cost)); // cost 기준 오름차순

// [
//   { weight: 5, cost: 20, name: '토마토' },
//   { weight: 10, cost: 10, name: '양파' },
//   { weight: 20, cost: 5, name: '당근' }
// ]
console.log(objList.sort((a, b) => b.cost - a.cost)); // cost 기준 내림차순

// [
//   { weight: 20, cost: 5, name: '당근' },
//   { weight: 10, cost: 10, name: '양파' },
//   { weight: 5, cost: 20, name: '토마토' }
// ]
console.log(objList.sort((a, b) => a.name.localeCompare(b.name))); // 이름 기준 사전순

'Javascript' 카테고리의 다른 글

JS : 이벤트 버블링, 이벤트 캡처링  (0) 2024.02.16
JS : 클로저란?  (0) 2024.02.09
JS : 일급 함수, 고차 함수란?  (0) 2024.02.09
JS : ES6에 추가된 문법 정리  (0) 2024.02.09
JS : this 바인딩  (0) 2024.02.07