diff --git a/snippets/flatten.md b/snippets/flatten.md index a31bbe2d0..708703f58 100644 --- a/snippets/flatten.md +++ b/snippets/flatten.md @@ -1,11 +1,17 @@ ### flatten -Flattens an array. +Flattens an array up to the specified depth. -Use a new array, `Array.concat()` and the spread operator (`...`) to cause a shallow denesting of any contained arrays. +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 flatten = arr => [].concat(...arr); +const flatten = (arr, depth = 1) => + depth != 1 + ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), []) + : arr.reduce((a, v) => a.concat(v), []); ``` ```js