How do I recursively remove consecutive duplicate elements from an array?

Suppose, we have an array of Number literals that contains some consecutive redundant entries like this −

const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];

We are supposed to write a function compress that takes in this array and removes all redundant consecutive entries in place. So that the output looks like this −

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

Let’s write the code for this function, we will be using recursion for this and the code for this will be −

Example

const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const compress = (arr, len = 0, canDelete = false) => {
   if(len 

Output

The output in the console will be −

[ 1, 2, 3, 1 ]
Updated on: 2020-08-25T07:15:11+05:30

684 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements