Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript recursive array flattening

I'm exercising and trying to write a recursive array flattening function. The code goes here:

function flatten() {
    var flat = [];
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] instanceof Array) {
            flat.push(flatten(arguments[i]));
        }
        flat.push(arguments[i]);
    }
    return flat;
}

The problem is that if I pass there an array or nested arrays I get the "maximum call stack size exceeded" error. What am I doing wrong?

like image 822
yxfxmx Avatar asked May 05 '15 08:05

yxfxmx


1 Answers

The problem is how you are passing the processing of array, if the value is an array then you are keep calling it causing an infinite loop

function flatten() {
    var flat = [];
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] instanceof Array) {
            flat.push.apply(flat, flatten.apply(this, arguments[i]));
        } else {
            flat.push(arguments[i]);
        }
    }
    return flat;
}

Demo: Fiddle

Here's a more modern version:

function flatten(items) {
  const flat = [];

  items.forEach(item => {
    if (Array.isArray(item)) {
      flat.push(...flatten(item));
    } else {
      flat.push(item);
    }
  });

  return flat;
}
like image 104
Arun P Johny Avatar answered Oct 15 '22 00:10

Arun P Johny