Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to make nested array flat?

That is to make this:

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

into:

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

like image 864
rsk82 Avatar asked May 17 '11 15:05

rsk82


People also ask

How do you flatten an array of arrays in Java?

Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the array into stream and add it to the list. Now convert this list into stream using stream() method. Now flatten the stream by converting it into array using toArray() method.


2 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]

It's note worthy that reduce isn't supported in IE 8 and lower.

developer.mozilla.org reference

like image 72
ChewOnThis_Trident Avatar answered Oct 05 '22 22:10

ChewOnThis_Trident


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"]
like image 28
elclanrs Avatar answered Oct 05 '22 22:10

elclanrs