ภาพรวม
เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ของค่าคงที่ที่อาจมีค่าซ้ำ ฟังก์ชันควรคืนอาร์เรย์ของอิลิเมนต์ที่ซ้ำน้อยที่สุด
ตัวอย่าง
อินพุต: 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 ]