Tell us what’s happening:
I still have two problems:
- My condition for pushing to the newArray is whether or not the element is an array, but because an empty array [ ] is still an array, my code looks inside the array for it’s first element which is undefined. So I am pushing ‘undefined’ to my newArray instead of ‘[ ]’.
If element is ‘[ ]’, Array.isArray([ ]) is true, so I recursively go to element[0], which is now undefined.
- I know that my recursive line of code:
flatten(e[0], finalArray)
only looks at the first element in an array e. I don’t get deep enough in my recursion.
when I try to ‘flatten’ [ 3 , [ [4] ] ], I only look at the first element in the array, the 3, but then ignore the 4 completely. I don’t know how to make that recursion look farther into the array [ 3 , [ [4] ] ].
Please help guide my thinking.
Your code so far
function steamrollArray(arr) {
let finalArray = [];
arr.forEach(e => flatten(e, finalArray));
console.log(finalArray);
return finalArray;
}
function flatten(e, finalArray) {
console.log(e, finalArray);
if (e == "[]") {console.log(true)}
if (!Array.isArray(e)) {
console.log('pushed ', e);
finalArray.push(e);
} else {
flatten(e[0], finalArray)
}
}
steamrollArray([1, [], [3, [[4]]]]);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Safari/605.1.15
.
Challenge: Steamroller
Link to the challenge: