일부 중복 값을 포함할 수 있는 리터럴 배열을 사용하는 JavaScript 함수를 작성해야 합니다.
이 함수는 가장 적은 횟수로 반복되는 모든 요소의 배열을 반환해야 합니다.
예를 들어 - 입력 배열이 -
인 경우const arr = [1,1,2,2,3,3,3];
그러면 출력은 다음과 같아야 합니다. -
const output = [1, 2];
1과 2가 가장 적은 횟수로 반복되기 때문에(2)
예시
const arr = [1,1,2,2,3,3,3];
const getLeastDuplicateItems = (arr = []) => {
const hash = Object.create(null);
let keys, min; arr.forEach(el => {
hash[el] = hash[el] || {
value: el, count: 0 };
hash[el].count++; });
keys = Object.keys(hash);
keys.sort(function (el, b) {
return hash[el].count - hash[b].count; });
min = hash[keys[0]].count;
return keys. filter(el => {
return hash[el].count === min;
}).
map(el => {
return hash[el].value;
});
}
console.log(getLeastDuplicateItems(arr)); 출력
콘솔의 출력은 -
[ 1, 2 ]