I am working on this challenge from FreeCodeCamp
Flatten a nested array. You must account for varying levels of nesting.
I am trying to solve it using recursion.
Here is my code:
function steamroller(arr) {
var flatArray = [];
function flatten(obj) {
if (!Array.isArray(obj)) {
return(obj);
}
for (var i in obj) {
return flatten(obj[i]);
}
}
flatArray.push(flatten(arr));
console.log(flatArray);
}
steamroller([1, [2], [3, [[4]]]]);
This logs:
Array [ 1 ]
I can see the problem, the return statement breaks the for loop so only the first value is returned.
However if I leave out the return and just use:
flatten(obj[i]);
I get back:
Array [ undefined ]
What should I do to fix this?
for ... inloops to iterate through arrays. Use.forEach()or a numeric index in an ordinaryforloop.