Is there an easy way to make a nested array flat?

To do this:

[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]

in:

['dog','cat','chicken','bear','mouse','horse']

+10
javascript arrays
source share
12 answers
 var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b); }); // flattened is [0, 1, 2, 3, 4, 5] 

Note that pruning is not supported in IE 8 and below.

developer.mozilla.org link

+22
source share

In modern browsers, you can do this without any external libraries in a few lines:

 Array.prototype.flatten = function() { return this.reduce(function(prev, cur) { var more = [].concat(cur).some(Array.isArray); return prev.concat(more ? cur.flatten() : cur); },[]); }; console.log([['dog','cat',['chicken', 'bear']],['mouse','horse']].flatten()); //^ ["dog", "cat", "chicken", "bear", "mouse", "horse"] 
+22
source share

Take underscore.js and use flatten .

 _.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]); 
+10
source share

How about this one liner code?

 [ ['dog','cat', ['chicken', 'bear'] ],[['mouse','horse'],'lion'] ].join().split(',') 

basically join will split the comma string from the nested array, and with split you can get a 1d array, okay? bonus it will work on all major browsers :)

therefore the output will be: -

 ["dog", "cat", "chicken", "bear", "mouse", "horse", "lion"] 
+6
source share

A small fix for the ChewOnThis_Trident solution, and it works fine:

 Array.prototype.flatten = function() { return this.reduce(function(a, b) { return a.concat(b); }, []); }; 
+5
source share

Assuming an array that is already unpacked from JSON, try the following:

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

It seems to work correctly on your input - see http://jsfiddle.net/alnitak/Ws7L5/

+4
source share

I know this is late, but I also came across a situation where I needed to make a multidimensional array into 1 array, and I did the following function.

 function nested(arr) { var noNest = arr.toString().split(',').filter(Boolean), i = 0; for(i;i<noNest.length; i++){ if(isNaN(noNest[i])){ return console.log(noNest); } else { noNest[i] = parseInt(noNest[i]); } } return console.log(noNest); } nested([[['a']], [['b']]]); 

It also accepts nested arrays inside the array under test and ensures that its single array as final placement places

+1
source share

This solution works great for me, and I find it especially convenient:

 function flattenArray(arr) { // the new flattened array var newArr = []; // recursive function function flatten(arr, newArr) { // go through array for (var i = 0; i < arr.length; i++) { // if element i of the current array is a non-array value push it if (Array.isArray(arr[i]) === false) { newArr.push(arr[i]); } // else the element is an array, so unwrap it else { flatten(arr[i], newArr); } } } flatten(arr, newArr); return newArr; } 
+1
source share

This is why I love javascript:

 function flattenArray(source) { return source.toString().split(','); } flattenArray([['dog', 'cat', ['chicken', 'bear']], ['mouse', 'horse']]); // -> ['dog','cat','chicken','bear','mouse','horse'] 
+1
source share

One approach you could take is to use the JSON2 library:

  • JSON.stringify array
  • Separate everything except the first and last [ and ] (or separate them all), and add them to the beginning and end.
  • JSON.parse it returns to JavaScript array

I assume, of course, you start with a JavaScript array. If its a string, then steps 1 and 3 do not matter.

0
source share

You can also use this open-source array-flatMap component.

Example:

 flatMap([[1, 2, 3], [4, 5, 6]], val => val) // => [1, 2, 3, 4, 5, 6] 

One of his tests shows this example related to this case:

 flatMap() should flatten the multi-dimensional array to a single-dimensional one 
0
source share

ES6 way to do it would be

 [['a', 'b'], ['c', 'd']].reduce((x,v) => [...x, ...v], []) 
0
source share

All Articles