That is to make this:
[ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]
into:
['dog','cat','chicken','bear','mouse','horse']
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.
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
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With