DEV Community

Cover image for Codewars - Delete occurrences of an element if it occurs more than n times
Nicolás Bost
Nicolás Bost

Posted on

Codewars - Delete occurrences of an element if it occurs more than n times

Salutations.

Rei Hino says bonjour

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

"Delete occurrences of an element if it occurs more than n times". In essence, trim parts in the middle of the array, without altering the order.

function deleteNth(arr,n){
  let counter = {"top": n , "undef": 0};

  for (let i = 0 ; i < arr.length ; i++ ){
    (counter[arr[i]]) ? null : counter[arr[i]] = 0;
    if (counter[arr[i]] < n){
      counter[arr[i]]++;
    } 
    else {
      arr[i] = undefined;
      counter.undef++;
    }
  }

  arr.sort((a,b) => 0);

  for (let i = 0 ; i < counter.undef ; i++){
    arr.pop();
  }

  return arr;
}
Enter fullscreen mode Exit fullscreen mode

It... works. Needs refactoring since it clearly doesn't follow any good practices, but I'm gonna move on to the next challenge.

Take care. Drink water 💧💧💧.

Previous

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay