1

I'm working on a simple recursive approach to flattening arrays, and I can't figure out where I'm going wrong. I've seen other threads on this (How to flatten nested array in javascript?) but I'm trying to do it without using .concat or .reduce.

This one keeps looping, but I'm not sure why- looks like it should hit the most nested array and return whatever characters within it.

Thanks!

var ret= []; var nested = [['a','b'],[],'c',['d','e']]; function flatten(arr) { for (i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { flatten(arr[i]); } else { ret.push(arr[i]); } } } flatten(nested); 

1 Answer 1

3

You forgot to declare i as a variable. It is being treated as a global variable.

for (var i = 0; i < arr.length; i++) { 

If you output the value of i in each iteration you will see your infinite loop problem,

0, 1, 3, 0, 1, 3, 0, 1, ... 
Sign up to request clarification or add additional context in comments.

4 Comments

That only explains part of the problem. The recursion causes later invocations of flatten to reuse that same global variable and overwrite the value in it while the loops in the outer invocations are still in the middle of iterating.
Andrew that did it! I don't think RJM's comment is true, as it works with the addition of 'var' in the for loop. Thanks all! Appreciate the help
@skdfsdfa, RJM is correct in their explanation of the issue. They were trying to add more context as to the reason why your code is causing an infinite loop.
I see, I thought they were specifying a separate issue instead of adding more context. Thanks again, this makes a lot more sense now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.