Tell us what’s happening:
I’m working on the Steamroller challenge in which we are to use recursion to flatten an array containing an unknown depth of nested arrays. With what I have written here, my function will flatten and return all values in the test cases EXCEPT the value of 4 which is nested within the final element of three of the test cases. I’ve tried plain old for loops using i or j to count up to the array length, I’ve tried for…of loops to iterate through all array elements. I’m not modifying the original array inside any loop. I’ve tried logging the array index and element values to the console. I don’t understand; why does it seem to be aware of the full array length, yet it exits the loop before iterating over the element that contains the nested 4?
Note: I did take a peek at the solutions but I would like to understand why my code doesn’t seem to be executing the loop as expected/intended.
–Matt
Your code so far
function steamrollArray(arr) {
let nested = [].concat(arr);
let output = [];
// console.log('nested is ', nested);
for (let x of nested) {
// console.log('x of nested is ', x);
output.push(recurse(x));
// console.log('output ', output);
}
return output.filter(x => x);
}
function recurse(element) {
// console.log('entered recurse with ',element);
if (!Array.isArray(element)) {
// console.log('returning ', element)
return element;
} else {
// console.log(element , 'is array');
for (let sub of element) {
// console.log('passing in ', sub);
return recurse(sub);
}
}
}
console.log(steamrollArray([[["a"]], [["b"]]]));
console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([1, [], [3, [[4]]]]));
console.log(steamrollArray([1, {}, [3, [[4]]]]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
.
Challenge: Steamroller
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller