Tell us what’s happening:
Describe your issue in detail here.
I tried it simply with a single reduce function to see what it gave back and it flattened everything but the deepest array. Then I attempted to add an index to the reduce function and also add a conditional statement that should have caught if the index was an array, to concatenate current[index] to the acc variable…but it tells me now that “acc” is undefined, and I am unsure why that is when the variable was declared at the beginning of the reduce function…
Your code so far
function steamrollArray(arr) {
let flattened = arr.reduce((acc, current, index) => {
if (Array.isArray(current)) {
acc.concat(current[index]);
} else {
acc.concat(current);
}
}, []);
return flattened;
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/112.0
ohh…okay…so recursion is absolutely necessary here it seems. I’ll try to make it recursive using the reduce function as the recursive return and add a base case.
yeah, I’ll try it…most times I shy away from recursion because I always managed to break the call stack lol…but hm, didn’t think of a while loop…even though those break the call stack as much as recursion does. But it’s an idea to try before a recursive call. I’ll have to think for a while to make a semi-successful recursive call. Might try that while loop first.
Oh, no, I meant with the new code I put up a couple of posts ago…this is the recursive code I added after the initial code, but this code is breaking the call stack:
function steamrollArray(arr) {
let copy = [...arr];
let flattened = [];
// base case
if (copy.length === 0) {
return flattened;
}
// recursion
if (Array.isArray(copy[0])) {
flattened.push(copy[0].reduce((acc, current) => acc.concat(current)), []);
} else {
flattened.push(copy[0]);
}
return steamrollArray(flattened, arr, arr.slice(1));
}
console.log(steamrollArray([1, [2], [3, [[4]]]]));
okay, I’ll try to do that. With the passing in of declared arguments, did you mean the “arr” variable I passed in at the end? I thought you had to pass them into the recursion so that those variables aren’t lost on each loop…that’s why I added them a the end, was I not supposed to? Or, actually should I replace that with “copy” since I used that instead of “arr” for the manipulation.
ohhhh…lol I get it…it’s not even looking for any parameters aside from that one passed in variable so it only has one it’s going to keep track of in the first place.