- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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