Home >Web Front-end >JS Tutorial >Codewars - Delete occurrences of an element if it occurs more than n times

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

Susan Sarandon
Susan SarandonOriginal
2025-01-06 10:49:43323browse

Salutations.

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

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;
}

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

The above is the detailed content of Codewars - Delete occurrences of an element if it occurs more than n times. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn