สมมติว่าเรามีอาร์เรย์ตัวเลข:
const arr = [1, 6, 3, 1, 3, 1, 6, 3];
เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ดังกล่าว หาตัวเลขที่ปรากฏจำนวนครั้งเป็นเลขคี่ (ไม่นับครั้งเดียว) และลบการเกิดครั้งสุดท้ายของตัวเลขเหล่านั้นออก
ตัวอย่าง
ในอาร์เรย์ข้างต้น 1 และ 3 ปรากฏ 3 ครั้ง (คี่) ดังนั้นลบครั้งที่ 3 ของทั้งคู่
อาร์เรย์ผลลัพธ์:
const output = [1, 6, 3, 1, 3, 6];
ตัวอย่างโค้ด
const arr = [1, 6, 3, 1, 3, 1, 6, 3];
const removeOddOccurence = (arr = []) => {
const copy = arr.slice();
const map = {};
arr.forEach((num, ind) => {
if(map.hasOwnProperty(num)) {
map[num][0]++;
map[num][1] = ind;
} else {
map[num] = [1, ind];
}
});
for(const key in map) {
const [freq, index] = map[key];
if(freq !== 1 && freq % 2 === 1) {
copy.splice(index, 1, '');
}
}
return copy.filter(el => el !== '');
};
console.log(removeOddOccurence(arr));
ผลลัพธ์
[1, 6, 3, 1, 3, 6]