0

I'm trying to write a recursive function that takes an array with nested arrays and puts all the values into a single array. Right now it works sometimes, but sometimes it doesn't.

function steamrollArray(arr) {
  var newArr = [];
  
  var func = function(array){
      for(i=0; i<array.length; i++){
        if(Array.isArray(array[i])){
          func(array[i]);
        }
        else {
          newArr.push(array[i]);
        }
      }
  };
  
  func(arr);
  return newArr;
}

When I run steamrollArray([1, [2], [3, [[4]]]]) it works, but if I run steamrollArray([[1], [[2]], [3, [[4]]]]); it doesn't include the 2 for some reason, and if I run steamrollArray([1, [], [3, [[4]]]]) my browser crashes. Thanks for any insight you can give!

karel
  • 5,489
  • 46
  • 45
  • 50
Alex
  • 270
  • 3
  • 6
  • I recommend writing to console and seeing where it crashes. Have you tried that yet? – Forklift Feb 10 '17 at 20:09
  • I did with the first and second examples. The first one does everything perfect, and the second example looks like everything is going to work, but it skips the second loop for some reason. I haven't even messed with the one that crashed the browser. – Alex Feb 10 '17 at 20:13

1 Answers1

3

Your problem is the i is in the global scope, you need to declare it local, so add let i

function steamrollArray(arr) {
  var newArr = [];
  
  var func = function(array){
      for(let i=0; i<array.length; i++){
        if(Array.isArray(array[i])){
          func(array[i]);
        }
        else {
          newArr.push(array[i]);
        }
      }
  };
  
  func(arr);
  return newArr;
}

console.log(steamrollArray([[1], [[2]], [3, [[4]]]]));
console.log(steamrollArray([1, [], [3, [[4]]]]));

Otherwise every time you call the function the i increases and you can go out of bond (like in your last example) or skipping some element (like in the second example)

rpadovani
  • 7,101
  • 2
  • 31
  • 50
  • 1
    Thank you so much! I kind of thought it had to do with that but I couldn't figure out why it would be acting like a global variable. Is there a difference between using 'let' and 'var'? – Alex Feb 10 '17 at 20:16
  • 2
    [difference between `let` and `var`](http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable). In this case: no effective difference. – GolezTrol Feb 10 '17 at 20:18
  • @Alex if you do not specify neither var or let then it will go in the global scope. – rpadovani Feb 10 '17 at 20:18