-
[JavaScript] 다중 조건 정렬JavaScript 2023. 10. 12. 21:16
const array = [[3,5,4], [1,4,3], [1,2,5]]
array 배열을 정렬할 때, 배열의 첫번째 값을 기준으로 오름차순 정렬을 하면 다음과 같이 할 수 있다.
array.sort((a,b) => a[0]-b[0]) console.log(array) //[[1,4,3], [1,2,5], [3,5,4]]
첫번째 값이 동일할 시 두번째 값을 기준으로 정렬하고 싶을 때가 있다.
그럴 땐 간단하게 다음과 같이 할 수 있다.
array.sort((a,b) => a[0]-b[0] || a[1]-b[1]) console.log(array) //[[1,2,5], [1,4,3], [3,5,4]]
앞의 연산이 0일 경우 두 값이 동일하다고 판단되어 다음 조건으로 판단된다.
array.sort((a,b) => { if(a[0] < b[0]) return -1 if(a[1] < b[1]) return -1 return -1 })
이 점을 이용하여 if 문 등을 통해 더 많은 다중 조건으로 정렬할 수 있고 숫자 이외에 문자로도 판별하여 정렬할 수 있다.
반응형'JavaScript' 카테고리의 다른 글
[PWA] Next.js 프로젝트에 PWA 적용하기 (0) 2023.10.25 [JavaScript] XState 기초 이해하기 (0) 2023.10.20 [JavaScript] 커링이란? (0) 2023.09.20 [JavaScript] Array.fill() 사용 시 주의할 점 (0) 2023.08.13 [JavaScript] 숫자로 된 문자열 정렬 (0) 2023.07.27