Deleting occurrences of an element if it occurs more than n times using JavaScript



Problem

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument.

Our function should delete elements from the array so that the resulting array contains no element appearing for more than the specified number (second argument).

Example

Following is the code −

 Live Demo

const arr = [4, 2, 3, 2, 4, 2, 2, 4];
const num = 2;
const deleteExcess = (arr = [], num = 1) => {
   const map = {};
   for(let i = 0; i < arr.length; i++){
      if(!map[arr[i]]){
         map[arr[i]] = 1;
      }else if(map[arr[i]] + 1 <= num){
         map[arr[i]]++
      };
   };
   const res = [];
   Object.keys(map).forEach(key => {
      for(i = 0; i < map[key]; i++){
         res.push(key);
      };
   });
   return res.map(Number);
};
console.log(deleteExcess(arr, num));

Output

[ 2, 2, 3, 4, 4 ]

Advertisements