maxBy
Returns the item with the maximum value based on a selector function.
1/**
2 * Returns the item with the maximum value based on a selector function.
3 *
4 * @param arr - Array of items.
5 * @param fn - Function that returns a numeric value from each item.
6 * @returns The item with the largest selected value, or undefined if empty.
7 */
8export function maxBy<T>(arr: T[], fn: (item: T) => number): T | undefined {
9 if (arr.length === 0) return undefined;
10
11 return arr.reduce((max, curr) =>
12 fn(curr) > fn(max) ? curr : max
13 );
14}
Flexible Selector Function
Allows precise control over which numeric property is used for comparison, supporting complex data shapes.
Efficient Single-Pass Logic
Uses
reduce
to iterate just once, providing optimal performance even on large datasets.Type-Safe and Generic
Preserves the original item type and structure with strong TypeScript type inference.
Safe Fallback Behavior
Returns
undefined
for empty arrays, helping avoid crashes or incorrect assumptions.
Tests | Examples
1test('maxBy - basic usage', () => {
2 const data = [{ x: 3 }, { x: 5 }, { x: 2 }];
3 expect(maxBy(data, item => item.x)).toEqual({ x: 5 });
4});
5
6test('maxBy - same values', () => {
7 const data = [{ x: 2 }, { x: 2 }];
8 expect(maxBy(data, item => item.x)).toEqual({ x: 2 });
9});
10
11test('maxBy - negative numbers', () => {
12 const data = [{ n: -5 }, { n: -1 }, { n: -10 }];
13 expect(maxBy(data, item => item.n)).toEqual({ n: -1 });
14});
15
16test('maxBy - empty array', () => {
17 expect(maxBy([], x => 1)).toBeUndefined();
18});
Common Use Cases
Finding Top Performer
Identify the item with the highest score, rating, or performance metric.
Pricing and Financial Insights
Extract the most expensive product, highest revenue item, or peak investment return.
Analytics Dashboards
Highlight top values like max CPU usage, longest duration, or highest conversion rate.
Gaming and Simulations
Determine the strongest entity, most valuable asset, or farthest distance.
Content Sorting and Filtering
Pick the most viewed, most recent, or most interacted-with item from a dataset.