789 B
789 B
title, type, language, tags, cover, dateModified
| title | type | language | tags | cover | dateModified | ||
|---|---|---|---|---|---|---|---|
| Flatten array | snippet | javascript |
|
angry-waves | 2020-10-22T20:23:47+03:00 |
Flattens an array up to the specified depth.
- Use recursion, decrementing
depthby1for each level of depth. - Use
Array.prototype.reduce()andArray.prototype.concat()to merge elements or arrays. - Base case, for
depthequal to1stops recursion. - Omit the second argument,
depth, to flatten only to a depth of1(single flatten).
const flatten = (arr, depth = 1) =>
arr.reduce(
(a, v) =>
a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
[]
);
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]