Using recursion to remove consecutive duplicate entries from an array - 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];

Example

Following is the code −

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

This will produce the following output in console −

[ 17, 12, 354, 1 ]

Updated on: 18-Sep-2020

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements