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];

Recursive Solution

The recursive approach modifies the array in-place by checking consecutive elements and removing duplicates:

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

const removeDuplicates = (arr, len = 0, deletable = false) => {
    if(len < arr.length){
        if(deletable){
            arr.splice(len, 1);
            len--;
        }
        return removeDuplicates(arr, len+1, arr[len] === arr[len+1])
    };
    return;
};

removeDuplicates(arr);
console.log(arr);
[ 17, 12, 354, 1 ]

How It Works

The function uses three parameters:

  • arr - The array to process
  • len - Current index position
  • deletable - Boolean flag indicating if current element should be removed

The algorithm compares each element with the next one. When consecutive duplicates are found, it removes the current element and adjusts the index accordingly.

Alternative Recursive Approach

Here's another recursive solution that creates a new array instead of modifying in-place:

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

const removeDuplicatesNew = (arr, index = 0, result = []) => {
    if (index >= arr.length) {
        return result;
    }
    
    // Add element if it's different from the previous one or it's the first element
    if (index === 0 || arr[index] !== arr[index - 1]) {
        result.push(arr[index]);
    }
    
    return removeDuplicatesNew(arr, index + 1, result);
};

const output = removeDuplicatesNew(arr);
console.log(output);
[ 17, 12, 354, 1 ]

Comparison

Method Memory Usage Original Array Complexity
In-place modification O(1) Modified O(n²) due to splice
New array creation O(n) Preserved O(n)

Conclusion

Recursive solutions offer elegant ways to remove consecutive duplicates. Choose the in-place method for memory efficiency or the new array approach for better performance and data preservation.

Updated on: 2026-03-15T23:18:59+05:30

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements