[Coding Test] Javascript nested sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const ASCENDING = 1
const DESCENDING = -1
const dir = DESCENDING
const priority = ['a','b']
const sortFunc = (a,b) => {
  for (let i=0; i<priority.length; i++){
    if (a[priority[i]] > b[priority[i]])
      return dir
    else if (a[priority[i]] < b[priority[i]])
      return -dir
  }
  return 0
}

const arr = [{a: 3, b: 4}, {a: 1, b: 2}, {a: 3, b: 2}]
arr.sort(sortFunc)
console.log(arr)

dirpriority만 바꿔서 쓰면된다.