Viết hàm xóa lần xuất hiện cuối cùng của các số xuất hiện số lần lẻ (>1) trong mảng.
Ví dụ: [1,6,3,1,3,1,6,3] → [1,6,3,1,3,6] (1 và 3 xuất hiện 3 lần, xóa lần thứ 3).
Ví dụ
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));
Kết quả
[1, 6, 3, 1, 3, 6]