Imagine having an array of numbers like this:
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];
The objective is to eliminate duplicate values only if they are next to each other. Therefore, the expected output for the given sample would be:
[2, 0, 2, 3, 0, 1]
Although I've made progress in solving this using a recursive method, there seems to be an issue preventing the generated result from being returned (although you can see it in the log before the return condition).
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];
const remAdjDups = (arr, output = []) =>
{
if (!arr.length)
{
console.log("Result before return: ", output);
return output;
}
if (arr[0] === arr[1])
{
arr.splice(1, 1);
remAdjDups(arr, output);
}
else
{
remAdjDups(arr.slice(1), output.concat(arr[0]));
}
}
let out = remAdjDups(input.slice());
console.log("output: ", out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Therefore, first and foremost, I would like to gain insights into what is happening with my approach, and secondly, I am open to any alternative solution (of any kind) that could tackle this problem.
Revised Solution
In case anyone is curious, I have successfully resolved this problem using recursion as follows. While I acknowledge that the filter solution is shorter and more elegant, I chose to practice solving it recursively.
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1, 1, 1, 1];
const remAdjDups = ([x, y, ...rest], out = []) =>
{
if (!rest.length)
return (x === y) ? [...out, x] : [...out, x, y];
else if (x === y)
return remAdjDups([x, ...rest], out);
else
return remAdjDups([y, ...rest], [...out, x]);
}
let out = remAdjDups(input.slice());
console.log("output: ", out);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}