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);
skdfsdfa
  • 77
  • 6

1 Answers1

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, ...
Andrew
  • 13,757
  • 13
  • 66
  • 84
  • 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. – RJM May 25 '17 at 19:52
  • 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 May 25 '17 at 19:57
  • @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. – Andrew May 25 '17 at 20:00
  • I see, I thought they were specifying a separate issue instead of adding more context. Thanks again, this makes a lot more sense now – skdfsdfa May 25 '17 at 20:33