Files
30-seconds-of-code/snippets/longestItem.md
Mathias Bynens 8ee50178f3 Avoid confusing prototype methods for static methods
Correct: `Array.from()` (it’s a static method)
Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method)

This patch uses the common `#` syntax to denote `.prototype.`.
2018-09-28 15:44:12 -04:00

21 lines
732 B
Markdown

### 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.prototype.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));
```
```js
longestItem('this', 'is', 'a', 'testcase'); // 'testcase'
longestItem(...['a', 'ab', 'abc']); // 'abc'
longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'
longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]
longestItem([1, 2, 3], 'foobar'); // 'foobar'
```