Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten nested arrays using recursion in JavaScript

I'm trying to flatten nested arrays while preserving the order, e.g. [[1, 2], 3, [4, [[5]]]] should be converted to [1, 2, 3, 4, 5].

I'm trying to use recursion in order to do so, but the code below does not work and I don't understand why. I know there are other methods to do it, but I'd like to know what's wrong with this.

function flatten (arr) {
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      flatten(arr);
    } else {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

flatten([[1, 2], 3, [4, [[5]]]]);

Thanks

like image 498
user1576121 Avatar asked Jun 01 '15 20:06

user1576121


People also ask

How do you flatten nested arrays?

The array method accepts an optional parameter depth , which specifies how deep a nested array structure should be flattened (default to 1 ). So to flatten an array of arbitrary depth, just call flat method with Infinity .

How does flattening an array work?

To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]]; and we need to return a new flat array with all the elements of the nested arrays in their original order.


2 Answers

When calling flatten recursively, you need to pass arr[i] to it and then concat the result with newArr. So replace this line:

flatten(arr);

with:

newArr = newArr.concat(flatten(arr[i]));
like image 113
OrenD Avatar answered Sep 22 '22 15:09

OrenD


Here's a common pattern that I regularly use for flattening nested arrays, and which I find a bit more clean due to its functional programming nature:

var flatten = (arrayOfArrays) =>
    arrayOfArrays.reduce((flattened, item) =>
        flattened.concat(Array.isArray(item) ? flatten(item) : [item]), []);

Or for those who like a shorter, less readable version for code golf or so:

var flatten=a=>a.reduce((f,i)=>f.concat(Array.isArray(i)?flatten(i):[i]),[]);
like image 27
Maurice Makaay Avatar answered Sep 20 '22 15:09

Maurice Makaay