skdfsdfa
skdfsdfa

Reputation: 77

recursive approach to nested arrays without using .concat or .reduce in JavaScript

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);

Upvotes: 1

Views: 116

Answers (1)

Andrew
Andrew

Reputation: 13853

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, ...

Upvotes: 3

Related Questions