DEV Community

Discussion on: Daily Challenge #237 - Delete Extra Occurrences

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Javscript

With the assumption that in a long array, most elements will be seen enough times, and we need to quickly drop them:

const delete_nth = (lst, n) => {
  const tired = new Set()
  const seen = new Map()
  return lst.filter(x => {
    if (tired.has(x)) return false
    const new_count = (seen.get(x) || 0) + 1
    if (new_count >= n) tired.add(x)
    else seen.set(x, new_count)
    return true
  })
}

Without that assumption:

const delete_nth = (lst, n) => {
  const seen = new Map()
  return lst.filter(x => {
    const count = seen.get(x) || 0
    if (count >= n) return false
    seen.set(x, count + 1)
    return true
  })
}