Limiting elements occurrences to n times in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers, arr, that may contain duplicates as the first argument, and a number, num, as the second and final argument.

The task of our function is to iterate through the array and check whether there exists some number that appears for more than n times in the array.

If there exists any such element, we should delete its extra occurrences to limit its occurrence to at most num.

For example, if the input to the function is −

Input

const arr = [4, 1, 3, 1, 4, 1, 3, 4, 2];
const num = 2;

Output

const output = [4, 1, 3, 1, 4, 3, 2];

Output Explanation

Both 4 and 1 appeared thrice, so their third appearance is deleted

Example

Following is the code −

 Live Demo

const arr = [4, 1, 3, 1, 4, 1, 3, 4, 2];
const num = 2;
const deleteExtra = (arr = [], num = 1) => {
   if(num === 0){
      return [];
   };
   const res = [];
   const map = {};
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      map[el] = (map[el] || 0) + 1;
      if(map[el] <= num){
         res.push(el);
      };
   };
   return res;
};
console.log(deleteExtra(arr, num));

Output

[ 4, 1, 3, 1, 4, 3, 2 ]

Updated on: 22-Apr-2021

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements