
https://school.programmers.co.kr/learn/courses/30/lessons/120880
function solution(numlist, n) {
return numlist
.sort((a, b) => b - a)
.sort((a, b) => Math.abs(a - n) - Math.abs(b - n));
}
✔ n으로부터의 거리가 같다면 더 큰 수를 앞에 오도록 배치하라는 조건에 의해 우선 내림차순 정렬부터 해준다.
✔ Math.abs(a - n) - Math.abs(b - n)에 의해 n과 더 가까운 수가 더 앞으로 정렬된다.
✔ Math.abs(a - n) === Math.abs(b - n)라면?
✔
Math.abs(a - n) === Math.abs(b - n)라면?
MDN - Array.prototype.sort()의compareFunction(a, b)에 따르면a - b가0인 경우 위치를 변경하지 않는다고 설명하고 있다.
따라서 이전에 더 큰 수가 앞에 오도록 정렬했기 때문에 이 위치가 뒤바뀌지 않고 유지된다.
function solution(numlist, n) {
return numlist
.sort((a, b) => Math.abs(a - n) - Math.abs(b - n) || b - a);
}
✔ 아니면 이렇게 || 연산자를 통해 차가 0인 경우 b - a가 실행되도록 하여 더 큰 수가 앞에 오도록 하는 방법도 있다.