JavaScript Snippet

Longest String and String-Length Maps

Difficulty: Easy

Two small but common questions on arrays of strings: which string is the longest, and how long is each one. The longest-string answer is a single `reduce`, with the tie-breaking rule explicit. The length-map answer is a single `map`, plus a tiny extension that sorts by length so the longest comes first. Both are short, but the patterns generalize to any "pick an extremum" or "shape the data for display" task.

Code Snippets
/

Longest String and String-Length Maps

Longest String and String-Length Maps

Two small but common questions on arrays of strings: which string is the longest, and how long is each one. The longest-string answer is a single `reduce`, with the tie-breaking rule explicit. The length-map answer is a single `map`, plus a tiny extension that sorts by length so the longest comes first. Both are short, but the patterns generalize to any "pick an extremum" or "shape the data for display" task.

JavaScript
Easy
2 snippets
arrays
string-manipulation
map-filter-reduce

1,012 views

22

The seed value (the second argument to reduce) is the empty string, which doubles as the answer for an empty input array and as the initial "best so far". The strict > comparison means ties go to whichever string came first; flip to >= to prefer the latest. For very large arrays this is O(n) and walks the array once, which beats sorting (O(n log n)) when you only need the single best item. If you need the longest N strings, sort by length and take a slice instead.