Recursive Array.flat
There was much talk about Array.prototype.flat
during its early stages, starting with the name alone. Many developers preferred the name flatten
but the spec differed from MooTools' implementation. MooTools would recursively flatten an array but the new, official flat
implementation defaults one level of flattening,.
The current implementation of Array.prototype.flat
is:
[1, 2, [3], [[4]]].flat(/* depth */); // [1,2,3,[4]]
.flat
only flattens arrays to one level by default, but what if you want a truly flattened array? You can use Infinity
and flat
's depth
argument to make that happen:
[1, 2, [3], [[4]], [[[[[[6]]]]]]].flat(Infinity); // [1,2,3,4,6]
I find the method name a bit misleading but I understand why they went to a single level. The method name smush
was thrown around, which would've been the worst method name since stringify
!
have an argument to specify the depth (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Parameters):