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.
1,012 views
22
// Reduce keeps a running 'best so far'. Ties go to the FIRST candidate
// because the comparison is strict greater-than.
const longest = (arr) =>
arr.reduce((best, s) => (s.length > best.length ? s : best), '');
console.log(longest(['cat', 'horse', 'mouse', 'lion']));
// 'horse' (5 chars; 'mouse' also has 5 but came later)
console.log(longest([]));
// '' (the seed value, sensible empty case)
// To return the LAST tied string instead, switch to >=.
const longestPreferLast = (arr) =>
arr.reduce((best, s) => (s.length >= best.length ? s : best), '');
console.log(longestPreferLast(['ab', 'cd', 'ef']));
// 'ef' (all same length, last one wins)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.
// The plain length map.
const lengths = (arr) => arr.map((s) => s.length);
console.log(lengths(['a', 'bb', 'ccc', 'dddd']));
// [1, 2, 3, 4]
// Pair each string with its length so the order survives a sort.
const byLength = (arr, dir = 'desc') =>
[...arr].sort((a, b) =>
dir === 'desc' ? b.length - a.length : a.length - b.length
);
console.log(byLength(['cat', 'horse', 'mouse', 'lion']));
// ['horse', 'mouse', 'lion', 'cat'] (descending)
console.log(byLength(['cat', 'horse', 'mouse', 'lion'], 'asc'));
// ['cat', 'lion', 'horse', 'mouse'] (ascending)
// Combined: top-N longest as a length-keyed list.
const topNLengths = (arr, n) =>
byLength(arr).slice(0, n).map((s) => ({ value: s, length: s.length }));
console.log(topNLengths(['cat', 'horse', 'mouse', 'lion'], 2));
// [{ value: 'horse', length: 5 }, { value: 'mouse', length: 5 }]map(s => s.length) is the obvious one-liner for a plain length list. The interesting addition is sorting the original strings by length: spread the input first so sort does not mutate the caller's array, then return a length-aware comparator. Defaulting to descending matches the common ask ("show me the longest first") and the optional 'asc' flag covers the inverse without adding a second function. The combined topNLengths helper is a useful pattern for building leaderboards or summary tables: shape and slice once, return the structured records.
