Changing an array in place using splice() JavaScript


We are required to write a function that, given an array arr and a number n, returns the array with elements repeating no more than n times. And we have to do all this without disturbing the indices of desired elements. So, let’s write the code for this function,

We will keep the count of all the elements in a hashmap and during iteration whenever the count of any element exceeds the maximum count we will splice that element. The code for this will be −

Example

const arr = [7, 26, 21, 41, 43, 2, 26, 24, 10, 26, 10, 10, 24, 35, 35,
35, 43, 26, 41, 7, 24, 24, 21, 24, 10, 35, 10, 7, 24, 7, 35, 26, 41,
35, 2, 43, 24, 2, 41, 26, 41, 7, 7, 26, 2, 10, 43, 10, 35, 41, 24, 7,
2, 2, 7, 2, 26, 24, 26, 43, 43, 21, 10, 28, 10];
const array = [12, 4, 2, 12, 32, 21, 67, 4, 32, 5];
const deleteExtra = (arr, n) => {
   const map = {};
   for(let i = 0; i < arr.length; i++){
      if(map[arr[i]]){
         if(map[arr[i]] >= n){
            arr.splice(i, 1);
            i--;
         }else{
            map[arr[i]]++;
         }
         continue;
      };
      map[arr[i]] = 1;
   }
};
deleteExtra(array, 1);
deleteExtra(arr, 2);
console.log(array);
console.log(arr);

Output

The output in the console will be −

[
   12, 4, 2, 32,
   21, 67, 5
]
[
   7, 26, 21, 41, 43, 2, 26,
   24, 10, 10, 24, 35, 35, 43,
   41, 7, 21, 2, 28
]

Updated on: 25-Aug-2020

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements