Using recursion to remove consecutive duplicate entries from an array in JavaScript


We are supposed to write a function that takes in an array of number/string literals. The function should remove all the redundant consecutive elements of the array without using extra memory space.

For example, if the input array is −

const arr = [17, 17, 17, 12, 12, 354, 354, 1, 1, 1];

Then the output should be −

const output = [17, 12, 354, 1];

Therefore, let’s write the code for this function −

Example

The code for this will be −

const arr = [17, 17, 17, 12, 12, 354, 354, 1, 1, 1];
const comp = (arr, len = 0, deletable = false) => {
   if(len < arr.length){
      if(deletable){
         arr.splice(len, 1);
         len--;
      }
      return comp(arr, len+1, arr[len] === arr[len+1])
   };
   return;
};
comp(arr);
console.log(arr);

Output

The output in the console will be −

[ 17, 12, 354, 1 ]

Updated on: 20-Oct-2020

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements