I am attempting to create a function that aims to eliminate any consecutive duplicate elements in an array recursively. It works with a global variable, however, I find that rather weak work around. I have based my code off of this code (Remove all consecutive duplicates from the string; language used: C++). I understand there are mutability differences between strings and arrays, but I don't exactly understand what is occurring to the stack in the background. Once the function is run, the global variable is correct, but the output from the function itself is not. Any explanation or direction would be greatly appreciated. Thank you!
This is not a homework question, I'm just trying to hammer recursion into my skull as it still throws me for a loop. Sorry for the pun.
//var testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1]
//compress(testArr); //[1,2,3,1] //<= expected result
//current output [1, 2, 2, 3, 3, 1, 1, 1]
var arr = [];
var compress = function(list) {
//var arr = [];
if (list.length === 0) {
return arr;
}
if (list.length === 1) {
arr.push(list[0]);
return list
}
if (list.length > 1 && list[0] !== list[1]) {
arr.push(list[0])
compress(list.slice(1,));
}
if (list.length > 1 && list[0] === list[1]) {
list.splice(0,1);
compress(list);
}
return list;
}
Using ECMAScript 6 features:
const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const compress = ([head, ...rest]) => {
if (!head) return [];
const tail = compress(rest);
return head === tail[0] ? tail : [head, ...tail];
}
console.log(compress(testArr));
As a side note, I'd like to note that functional approach is a little bit shorter (yeah, I know that the question is about recursive approach):
const testArr = [1, 1, 2, 2, 3, 3, 1, 1, 1];
const output = testArr.reduce((list, next) => list.slice(-1)[0] === next ? list : [...list, next], []);
console.log(output);
Because list.slice(1,) copies the array, so in the recursive call list is not the original array. Changing that does not change the original array. You have to change the list you want to return (passing the result up the call stack):
list = [list[0], ...compress(list.slice(1,))];
Maybe shorter:
const compress = arr => arr.length > 1
? arr[0] === arr[1]
? compress(arr.slice(1))
: [arr[0], ...compress(arr.slice(1))]
: arr;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With