I have the following code that flattens a multidimensional array
var x = [[[2, 3], 4], 5, [6, 7]];
function flatten(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].constructor === Array) {
subArr = arr[i];
// Shift the array down based on the space needed for the sub array
for (var j = arr.length + subArr.length - 2; j > i + subArr.length - 1; j--) {
arr[j] = arr[j - subArr.length + 1];
}
// Insert sub array elements where they belong
for (var k = 0; k < subArr.length; k++) {
arr[i + k] = subArr[k];
}
// Look at arr[i] again in case the first element in the subarray was another array;
i--;
}
}
}
flatten(x);
JSBin here: http://jsbin.com/gazagemabe/edit?js,console
I want to do this using recursion but I end up getting stuck. I'm trying to do it without keeping a temp array, but then things seem to fall out of whack. I feel like I'm missing some core principal of recursion.
I realize I need a base case. The only case I can come up with is when the array currently in flatten has no subarrays. But since I'm always passing the array by reference, I have nothing to return.
My psuedo-code is
function flatten(arr)
loop through arr
if arr[index] is an array
increase the array length arr[index] length
flatten(arr[index])
else
// unsure what to do here to modify the original array