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

Nicolás Bost @dantedinopegassi

About: Yo tratando de usar un 𝒷𝓁ℴ𝑔 para jugar menos jueguitos

Joined:
Dec 30, 2024

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

Publish Date: Jan 6
0 0

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

Comments 0 total

    Add comment