Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 ?
How the Algorithm Works
The recursive function works by checking each element against its next element. When consecutive duplicates are found, the function removes the current element and adjusts the index accordingly. This process continues until all duplicates are removed.
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 ]
Step-by-Step Breakdown
Let's trace through the execution with a simpler example:
const testArr = [1, 1, 2, 2, 3];
const removeConsecutiveDuplicates = (arr, index = 0, shouldDelete = false) => {
console.log(`Step: index=${index}, shouldDelete=${shouldDelete}, array=[${arr}]`);
if(index < arr.length){
if(shouldDelete){
console.log(`Removing element at index ${index}: ${arr[index]}`);
arr.splice(index, 1);
index--;
}
return removeConsecutiveDuplicates(arr, index + 1, arr[index] === arr[index + 1]);
}
return arr;
};
removeConsecutiveDuplicates(testArr);
console.log("Final result:", testArr);
Key Points
- The function uses three parameters: the array, current index, and a flag indicating if the current element should be deleted
- When
deletableis true, the current element is removed usingsplice() - The index is decremented after deletion to account for the shifted array elements
- The recursion continues by comparing the current element with the next one
Alternative Approach Using Filter
For comparison, here's a non-recursive approach that creates a new array:
const arr2 = [17, 17, 17, 12, 12, 354, 354, 1, 1, 1];
const result = arr2.filter((item, index) => {
return index === 0 || item !== arr2[index - 1];
});
console.log("Original:", arr2);
console.log("Filtered:", result);
Original: [ 17, 17, 17, 12, 12, 354, 354, 1, 1, 1 ] Filtered: [ 17, 12, 354, 1 ]
Conclusion
The recursive approach modifies the original array in-place without using extra memory space, making it memory-efficient. However, the filter method is more readable and follows functional programming principles, though it creates a new array.
