 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 < 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 ]
Advertisements
 