

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 ]
- Related Questions & Answers
- How to remove duplicate elements from an array in JavaScript?
- Using recursion to remove consecutive duplicate entries from an array - JavaScript
- Using recursion to remove consecutive duplicate entries from an array in JavaScript
- How do I make an array with unique elements (remove duplicates) - JavaScript?
- How to remove duplicate elements of an array in java?
- How do I remove a particular element from an array in JavaScript
- How to redundantly remove duplicate elements within an array – JavaScript?
- Removing duplicate elements from an array in PHP
- How do I remove a string from an array in a MongoDB document?
- How do I remove multiple elements from a list in Java?
- Java Program to Remove duplicate elements from ArrayList
- Remove/ filter duplicate records from array - JavaScript?
- How do I push elements to an existing array in MongoDB?
- C# program to remove duplicate elements from a List
- How can I remove a specific item from an array JavaScript?
Advertisements