Check out this cool function that takes a multi-dimensional array and converts it into a single-dimensional array using recursion. It's pretty nifty because it doesn't use any global variables, so everything is contained within the function itself.
Take a look at the code below:
function flattenArray(someArr) {
var results = [];
if(isArrayLike(someArr)) {
for(var i = 0; i != someArr.length; i++) {
flattenArray(someArr[i])
}
} else {
results.push(someArr);
}
return results;
}
The tricky part here is that the function will always return an empty array since each recursive call clears the array. How can we work around this without resorting to using global variables?
Let's assume that isArrayLike() is a function that determines whether a given input is array-like or not.