เราจำเป็นต้องเขียนฟังก์ชัน 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 ]