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))); // 이름 기준 사전순