Recursive Array.flat
Publikováno: 17.5.2019
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 was only one level of flattening. The current implementation of Array.prototype.flat is: [1, 2, [3], […]
The post Recursive Array.flat appeared first on David Walsh Blog.
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 was only one level of flattening.
The current implementation of Array.prototype.flat
is:
[1, 2, [3], [[4]]].flat(); // [1,2,3,[4]]
.flat
only flattens arrays to one levels, but what if you want a truly flattened array? MDN provides a really great solution to recursively flatten an array:
function flattenDeep(arr1) { return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []); } flattenDeep([1, 2, [3], [[4]], [[[[[[6]]]]]]]) // [1,2,3,4,6]
To recursively flatten an array, you must use Array.prototype.reduce
with .flat
.
I wish a second argument was added to flat
to represent if you wanted a recursive flatten, with the default being false
to keep the current behavior. 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
!
The post Recursive Array.flat appeared first on David Walsh Blog.