pineapplecakes pineapplecakes - 9 months ago 29
Javascript Question

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

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.

Answer Source

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++){