diff --git a/README.md b/README.md index 63a9f1aef..feb5e16fe 100644 --- a/README.md +++ b/README.md @@ -1255,14 +1255,14 @@ findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 Returns the index of the last element for which the provided function returns a truthy value. Use `Array.map()` to map each element to an array with its index and value. -Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one. +Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one. ```js const findLastIndex = (arr, fn) => arr .map((val, i) => [i, val]) - .filter(val => fn(val[1], val[0], arr)) - .slice(-1)[0][0]; + .filter(([i, val]) => fn(val, i, arr)) + .pop()[0]; ```
diff --git a/docs/array.html b/docs/array.html index 50db30768..7b411c070 100644 --- a/docs/array.html +++ b/docs/array.html @@ -146,11 +146,11 @@
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
 

findLast

Returns the last element for which the provided function returns a truthy value.

Use Array.filter() to remove elements for which fn returns falsey values, Array.pop() to get the last one.

const findLast = (arr, fn) => arr.filter(fn).pop();
 
findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
-

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

Use Array.map() to map each element to an array with its index and value. Use Array.filter() to remove elements for which fn returns falsey values, Array.slice(-1) to get the last one.

const findLastIndex = (arr, fn) =>
+

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

Use Array.map() to map each element to an array with its index and value. Use Array.filter() to remove elements for which fn returns falsey values, Array.pop() to get the last one.

const findLastIndex = (arr, fn) =>
   arr
     .map((val, i) => [i, val])
-    .filter(val => fn(val[1], val[0], arr))
-    .slice(-1)[0][0];
+    .filter(([i, val]) => fn(val, i, arr))
+    .pop()[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) =>
   arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);