As we know, to flatten the array [[0, 1], [2, 3], [4, 5]]
by using the method reduce()
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
});
So how to flatten this array [[[0], [1]], [[2], [3]], [[4], [5]]]
to [0, 1, 2, 3, 4, 5]
?
Best Answer
Perfect use case for recursion, which could handle even deeper structure:
Alternatively, as an Array method:
EDIT #1: Well, think it a little bit functional way (except for the named recursion which should be using Y-combinator for pure functional :D).
Let's adopt some ES6 syntax which makes it even shorter, in one line.
But remember, this one cannot be applied as an array method, because arrow functions don't have theirs own
this
.EDIT #2: With the latest
Array.prototype.flat
proposal this is super easy. The array method accepts an optional parameterdepth
, which specifies how deep a nested array structure should be flattened (default to1
).So to flatten an array of arbitrary depth, just call
flat
method withInfinity
.