I'm trying to flatten an array with randomly nested arrays inside. I'm not sure why the function I wrote ends up in an infinite loop:
let array = [1, 2, [3]]
var final_array = [] 
function flattener(array){
  for(i = 0; i < array.length; i++){
    if(array[i] instanceof Array){
      flattener(array[i])
    }else{
      final_array.push(array[i])
    }
  }
}
flattener(array)
What I think SHOULD happen is:
When I'm in the for loop checking for [3], it goes into the if statement, flattener gets called again, it resolves, and then I exit the if statement.
Instead, the if statement keeps calling to check [3] infinitely, and I'm not sure why this happens.
The problem is you didn't declare the i variable, so it's leaking into the global space and being reset when it recurses.
Change:
for(i = 0; i < array.length; i++){
To:
for(var i = 0; i < array.length; i++){
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With