문제
첫 번째이자 유일한 인수로 숫자 배열, arr를 취하는 JavaScript 함수를 작성해야 합니다.
배열 arr에 일부 중복 항목이 포함될 수 있습니다. 우리 함수는 가장 적은 횟수로 나타나는 요소가 먼저 배치되고 빈도가 증가하는 요소가 뒤따르는 방식으로 배열을 정렬해야 합니다.
배열에서 두 개의 요소가 같은 횟수로 나타나면 오름차순으로 배치해야 합니다.
예를 들어, 함수에 대한 입력이
인 경우입력
const arr = [5, 4, 5, 4, 2, 1, 12];
출력
const output = [1, 2, 12, 4, 4, 5, 5];
출력 설명
숫자 1, 2, 12는 모두 한 번 표시되므로 오름차순으로 정렬된 다음 4와 5가 모두 두 번 표시됩니다.
예시
다음은 코드입니다 -
const arr = [5, 4, 5, 4, 2, 1, 12];
const sortByAppearance = (arr = []) => {
arr.sort((a, b) => a - b);
const res = [];
const searched = {};
const countAppearance = (list, target) => {
searched[target] = true;
let count = 0;
let index = list.indexOf(target);
while(index !== -1){
count++;
list.splice(index, 1);
index = list.indexOf(target);
};
return count;
};
const map = [];
arr.forEach(el => {
if(!searched.hasOwnProperty(el)){
map.push([el, countAppearance(arr.slice(), el)]);
};
});
map.sort((a, b) => a[1] - b[1]);
map.forEach(([num, freq]) => {
while(freq){
res.push(num);
freq--;
}
});
return res;
};
console.log(sortByAppearance(arr)); 출력
[1, 2, 12, 4, 4, 5, 5]