Skip to content
Advertisement

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

i’m trying to create a function that gives me an array of numbers with a limitation of repetition for each number. for example

([1,1,3,3,7,2,2,2,2], 3) 

should give me

[1, 1, 3, 3, 7, 2, 2, 2]

it deletes a [2] because the max repetition of numbers is 3.

here is my code but i don’t know why it doesn’t work:

function deleteNth(arr,n){
  var results = [];
  for(var i=0; i<arr.length; i++){
  if (count(results, arr[i])<=n) {
    results.push(arr[i]);
  }
}
return results;
}
function count(array, what){
  var count =0;
  for (var i=0; i<array.length; i++){
    if (array[i]===what){
      count++;
    }
  }
  return count;
}
console.log(deleteNth([1,1,3,3,7,2,2,2,2], 3));

Advertisement

Answer

I would use a reduce to iterate over all elements of the array and a dictionary to keep track of the number of times I found an element.

Here’s an example:

const filterReps = (arr, maxReps) => {
  return arr.length ? arr.reduce((acc, num, i) => {
    // Add this number to our dictionary,
    // if already present add +1 to it's count
    acc.found[num] = acc.found[num] ? ++acc.found[num] : 1

     // If the dictionary says the number has been found less or equal
     // times to our max repetitions, push it into the accumulating array
    if (acc.found[num] <= maxReps)
      acc.arr.push(num)

    // If this is the final iteration, just return only the result array
    // and not the dictionary
    return i === nums.length - 1 ? acc.arr : acc
  }, { found: {}, arr: [] }) : arr
}

const nums = [1, 1, 1, 1, 2, 2, 2, 2]
console.log(filterReps(nums, 3))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement