ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลขเป็นอาร์กิวเมนต์แรกและตัวเลขเป็นอาร์กิวเมนต์ที่สอง
ฟังก์ชันของเราควรลบองค์ประกอบออกจากอาร์เรย์เพื่อให้อาร์เรย์ที่เป็นผลลัพธ์ไม่มีองค์ประกอบปรากฏเกินกว่าจำนวนที่ระบุ (อาร์กิวเมนต์ที่สอง)
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [4, 2, 3, 2, 4, 2, 2, 4];
const num = 2;
const deleteExcess = (arr = [], num = 1) => {
const map = {};
for(let i = 0; i < arr.length; i++){
if(!map[arr[i]]){
map[arr[i]] = 1;
}else if(map[arr[i]] + 1 <= num){
map[arr[i]]++
};
};
const res = [];
Object.keys(map).forEach(key => {
for(i = 0; i < map[key]; i++){
res.push(key);
};
});
return res.map(Number);
};
console.log(deleteExcess(arr, num)); ผลลัพธ์
[ 2, 2, 3, 4, 4 ]