Tell us what’s happening:
So I just getting frustrated. I use the flat works like charm. However the the test are to use an alternative. the code is suppose to check for an array and the flatten the array until there is just one level.
Its not working. Ugh
Your code so far
function steamrollArray(arr) {
var flattened = [];
for (let i = 0; i < arr.length; i++) {
const current = arr[i];
if (!Array.isArray(current)) {
flattened.push(current);
continue;
}
for (let j = 0; j < current.length; j++) {
flattened.push(current[j])
}
}
console.log(flattened)
return flattened;
}
steamrollArray([1, [2], [3, [[4]]]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.
First of all, don’t get frustrated. A lot of people have trouble with this one.
So, looking at your solution, you are attempting and iterative solution - using nested loops. The problem is that you need as many nested loops as you have nested arrays., That is why yours fails when there is more than two levels of arrays. What if there are 10 levels? 100 levels?
Most people who do this use a recursive solution, a function that keeps calling itself. The idea would be that as you go through each array, if an element is itself and array, you’re going to call that subarray with the flattener (either your parent function of a helper function). These are not easy when you are learning.
I know there must be a loop solution. I suspect that you could do it with a moving reference that traverses the tree-like structure. I’ll have to think about that.
But I think you’re going to have better luck trying to figure out a recursive solution.
Your outer loop and conditional are handling arrays that are nested one deep. The inner loop is pulling out elements that are nested two deep. Or in other words, this code is handling the 1 (outer loop/conditional), 2, and 3, in the example and pulling out a [[4]] (all three from the inner loop).
I know I used recursion for my initial solution by calling the steamroll function again when an array was found in an outer array (like your conditional).
I just went back and did the challenge again without recursion and that solution has the same logic, but you will need to use a while loop and the array functions concat(), slice(), and shift() to flatten the array in place (like a stack).
For me, the recursive solution was easier than the iterative one because I find it easy to figure out how to do something once (like you did) and then recursion just tells the computer to keep doing the same thing as long as necessary.