Skip to content

Instantly share code, notes, and snippets.

@Alonso-Pablo
Last active December 31, 2021 16:37
Show Gist options
  • Save Alonso-Pablo/3e9eeb649d47b6e8dfc27330e814d4c5 to your computer and use it in GitHub Desktop.
Save Alonso-Pablo/3e9eeb649d47b6e8dfc27330e814d4c5 to your computer and use it in GitHub Desktop.
Saves the characters that are repeated within the array in a unique index in a dictionary. If the character was repeated more than the times indicated by the second parameter of the function, it is deleted from the result.
function deleteNth(arr,n){
const result = []
const dict = {}
for (const num of arr) {
if (num in dict) {
if (dict[num] < n) {
result.push(num)
}
dict[num]++
} else {
dict[num] = 1
result.push(num)
}
}
return result
}
deleteNth(
// Array with repeated numbers,
// Maximum number of times the number can be repeated
)
// Example:
// deleteNth( [1,1,1,2,3,4,5,1,1,3,1,4,1], 2)
// Output: [ 1, 1, 2, 3, 4, 5, 3, 4 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment