JSFiddle - React, Tailwind, and code Playground
by Sebastian Kay
JavaScript
function deleteNth(arr, n) {
const resultMap = new Map();
const resultList = [];
for (num of arr) {
const count = resultMap.has(num) ? resultMap.get(num) + 1 : 1;
if (count <= n) {
resultMap.set(num, count);
resultList.push(num);
}
}
return resultList;
}
const Test1 = deleteNth([20,37,20,21], 1); // [20,37,21]
const Test2 = deleteNth([1,1,3,3,7,2,2,2,2], 3); // [1, 1, 3, 3, 7, 2, 2, 2]
console.log(Test1 + " [20,37,21]");
console.log(Test2 + " [1, 1, 3, 3, 7, 2, 2, 2]");