From 22331697df69b65ac7ed619dd6608a454574ae3d Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Thu, 14 Dec 2017 16:10:43 +0200 Subject: [PATCH] Create flatten-array-up-to-depth.md In reference to #100. --- snippets/flatten-array-up-to-depth.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 snippets/flatten-array-up-to-depth.md diff --git a/snippets/flatten-array-up-to-depth.md b/snippets/flatten-array-up-to-depth.md new file mode 100644 index 000000000..d28af98fb --- /dev/null +++ b/snippets/flatten-array-up-to-depth.md @@ -0,0 +1,13 @@ +### Flatten array up to depth + +Use recursion, decrementing `depth` by 1 for each level of depth. +Use `Array.reduce()` and `Array.concat()` to merge elements or arrays. +Base case, for `depth` equal to `1` stops recursion. +Omit the second element, `depth` to flatten only to a depth of `1` (single flatten). + +```js +const flattenDepth = (arr, depth = 1) => + depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth (v, depth-1) : v), []) + : arr.reduce((a,v) => a.concat(v),[]); +// flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5] +```