minBy
Returns the item with the minimum value based on a selector function.
1/**
2 * Returns the item with the minimum 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 smallest selected value, or undefined if empty.
7 */
8export function minBy<T>(arr: T[], fn: (item: T) => number): T | undefined {
9 if (arr.length === 0) return undefined;
10
11 return arr.reduce((min, curr) =>
12 fn(curr) < fn(min) ? curr : min
13 );
14}
Custom Selector Flexibility
Supports complex objects by letting you define how to extract the numeric value for comparison.
Concise and Efficient
Uses a single-pass
reduce
for optimal performance without sorting or additional memory usage.Type-Safe and Generic
Maintains the full item structure while ensuring type safety via TypeScript generics.
Graceful Empty Handling
Returns
undefined
if the array is empty, avoiding runtime errors or misleading results.
Tests | Examples
1test('minBy - basic usage', () => {
2 const data = [{ x: 3 }, { x: 1 }, { x: 4 }];
3 expect(minBy(data, item => item.x)).toEqual({ x: 1 });
4});
5
6test('minBy - same values', () => {
7 const data = [{ x: 2 }, { x: 2 }];
8 expect(minBy(data, item => item.x)).toEqual({ x: 2 });
9});
10
11test('minBy - negative numbers', () => {
12 const data = [{ n: -5 }, { n: 0 }, { n: 2 }];
13 expect(minBy(data, item => item.n)).toEqual({ n: -5 });
14});
15
16test('minBy - empty array', () => {
17 expect(minBy([], x => 1)).toBeUndefined();
18});
Common Use Cases
Finding Cheapest Option
Select the item with the lowest price, cost, or fee in a product list.
Performance Metrics
Identify the fastest response time, smallest size, or lowest score in a dataset.
Data Selection for Display
Pick the most relevant or optimal record (e.g., earliest deadline, lowest priority).
Analytics and Reporting
Extract minimum values across structured records like logs, usage stats, or financial data.
Game or Simulation Logic
Find the entity with the least health, distance, or resource usage for real-time decisions.