- Trending Categories
- 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
Using recursion to remove consecutive duplicate entries from an array in 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];
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [17, 17, 17, 12, 12, 354, 354, 1, 1, 1]; const comp = (arr, len = 0, deletable = false) => { if(len < arr.length){ if(deletable){ arr.splice(len, 1); len--; } return comp(arr, len+1, arr[len] === arr[len+1]) }; return; }; comp(arr); console.log(arr);
Output
The output in the console will be −
[ 17, 12, 354, 1 ]
Advertisements