Return the highest-scoring item by function or nested path
A leaderboard widget shows a “Top performer” badge. Depending on the page, “best” means the most points, the highest rating, or the most recent activity, and some players have no score yet. Implement pickBest(items, score), which returns the item with the highest score.
pickBest(items, score) // => the best item, or undefined
score argumentscore(item, index) that returns the item’s score. Call it at most once per item: in production it can be expensive (for example, computing a weighted rating).'stats.points' reads item.stats.points. If any step is missing or is null/undefined, the score is undefined (do not throw).>. Scores are numbers or strings (for example ISO dates, which compare correctly as strings).null, undefined, or NaN. Negative scores and 0 are valid.undefined when items is empty or no item has a valid score.score for them.items.const players = [
{ name: 'Ana', stats: { points: 42 }, lastSeen: '2025-03-01' },
{ name: 'Ben', stats: { points: 57 }, lastSeen: '2025-02-11' },
{ name: 'Cy', stats: null, lastSeen: '2025-03-09' },
{ name: 'Dot', stats: { points: 57 }, lastSeen: '2024-12-30' },
];
pickBest(players, 'stats.points'); // => Ben (Dot ties but comes later)
pickBest(players, 'lastSeen'); // => Cy
pickBest(players, (p) => p.name.length); // => Ana (3 letters, first of the ties)
pickBest(players, (p) => p.stats && -p.stats.points); // => Ana (Cy scores null and is skipped)
pickBest([], 'score'); // => undefined