diff --git a/README.md b/README.md index b33e5fa43..5c51180bd 100644 --- a/README.md +++ b/README.md @@ -1277,9 +1277,7 @@ Omit the second argument, `depth` to flatten only to a depth of `1` (single flat ```js 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), []); + arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); ```
diff --git a/docs/index.html b/docs/index.html index 753d9c5eb..02031c09e 100644 --- a/docs/index.html +++ b/docs/index.html @@ -221,9 +221,7 @@ Object.assig .slice(-1)[0][0];
findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3)
 

flatten

Flattens an array up to the specified 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 argument, depth to flatten only to a depth of 1 (single flatten).

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), []);
+  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]
 

forEachRight

Executes a provided function once for each array element, starting from the array's last element.

Use Array.slice(0) to clone the given array, Array.reverse() to reverse it and Array.forEach() to iterate over the reversed array.

const forEachRight = (arr, callback) =>
diff --git a/snippets/flatten.md b/snippets/flatten.md
index 854d27a53..029fbf3f7 100644
--- a/snippets/flatten.md
+++ b/snippets/flatten.md
@@ -9,11 +9,7 @@ Omit the second argument, `depth` to flatten only to a depth of `1` (single flat
 
 ```js
 const flatten = (arr, depth = 1) =>
-  arr.reduce(
-    (a, v) =>
-      a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
-    [],
-  );
+  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
 ```
 
 ```js