Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a JavaScript array -- why isn't this working?

Tags:

javascript

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.

like image 816
pineapplecakes Avatar asked Dec 10 '22 12:12

pineapplecakes


1 Answers

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++){
like image 177
CrackpotCrocodile Avatar answered Jan 01 '23 15:01

CrackpotCrocodile