depth
by 1
for each level of depth.Array.prototype.reduce()
and Array.prototype.concat()
to merge elements or arrays.depth
equal to 1
stops recursion.depth
, to flatten only to a depth of 1
(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]
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️