diff --git a/README.md b/README.md index 4a1d737ab..6fc1215f1 100644 --- a/README.md +++ b/README.md @@ -1849,11 +1849,14 @@ last([1, 2, 3]); // 3 ### longestItem Takes any number of iterable objects or objects with a `length` property and returns the longest one. +If multiple objects have the same length, the first one will be returned. +Returns `undefined` if no arguments are provided. -Use `Array.reduce()` to collect the longest element. Returns [] for empty array. +Use `Array.reduce()`, comparing the `length` of objects to find the longest one. ```js -const longestItem = (...vals) => [...vals].reduce((a, x) => (a.length > x.length ? a : x), []); +const longestItem = (val, ...vals) => + [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); ```
diff --git a/docs/array.html b/docs/array.html index 90912d0ad..8e9865463 100644 --- a/docs/array.html +++ b/docs/array.html @@ -268,7 +268,8 @@ JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'

last

Returns the last element in an array.

Use arr.length - 1 to compute the index of the last element of the given array and returning it.

const last = arr => arr[arr.length - 1];
 
last([1, 2, 3]); // 3
-

longestItem

Takes any number of iterable objects or objects with a length property and returns the longest one.

Use Array.reduce() to collect the longest element. Returns [] for empty array.

const longestItem = (...vals) => [...vals].reduce((a, x) => (a.length > x.length ? a : x), []);
+

longestItem

Takes any number of iterable objects or objects with a length property and returns the longest one. If multiple objects have the same length, the first one will be returned. Returns undefined if no arguments are provided.

Use Array.reduce(), comparing the length of objects to find the longest one.

const longestItem = (val, ...vals) =>
+  [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a));
 
longestItem('this', 'is', 'a', 'testcase'); // 'testcase'
 longestItem(...['a', 'ab', 'abc']); // 'abc'
 longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
diff --git a/snippets/longestItem.md b/snippets/longestItem.md
index 5cb85504a..c557c0bf6 100644
--- a/snippets/longestItem.md
+++ b/snippets/longestItem.md
@@ -7,7 +7,8 @@ Returns `undefined` if no arguments are provided.
 Use `Array.reduce()`, comparing the `length` of objects to find the longest one.  
 
 ```js
-const longestItem = (val, ...vals) => [val, ...vals].reduce((a, x) => x.length > a.length ? x : a);
+const longestItem = (val, ...vals) =>
+  [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a));
 ```
 
 ```js