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

JavascriptWeb DevelopmentObject Oriented Programming

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 < arr.length){
if(canDelete){
arr.splice(len, 1);
len--;
}
return compress(arr, len+1, arr[len] === arr[len+1])
};
return;
};
compress(testArr);
console.log(testArr);

## Output

The output in the console will be −

[ 1, 2, 3, 1 ]
Published on 25-Aug-2020 10:44:12