minBy()
minBy<
T>(array,iteratee):T
minBy<
T>(array,iteratee):T|undefined
Returns the element with the minimum value computed by iteratee.
Type Parameters
T: T
The type of elements in the array.
Parameters
Overload 1:
array: readonly [T, T]
The array to iterate over.
iteratee: (value) => number
A function that returns the value to compare.
Overload 2:
array: readonly T[]
The array to iterate over.
iteratee: (value) => number
A function that returns the value to compare.
Returns: T
The element with the minimum value, or undefined if empty.
Since
2.0.0
Performance
O(n) time, O(1) space.
Also known as
min (Radashi) · minBy (Lodash, es-toolkit, Remeda, Ramda) · ❌ (Effect, Modern Dash, Antfu)
Example
minBy([{ name: 'John', age: 25 }, { name: 'Bob', age: 20 }] as const, (u) => u.age);
// => { name: 'Bob', age: 20 }
minBy([{ name: 'John', age: 25 }, { name: 'Bob', age: 20 }], (u) => u.age);
// => { name: 'Bob', age: 20 }
minBy([], (x) => x);
// => undefined
How it works?
Finds the element with the minimum value computed by iteratee.
Use Cases
Find the cheapest product 📌
Identify the lowest-priced item for discounts or budget analysis. Perfect for e-commerce, price comparison, or deal finders.
const cartItems = [
{ name: "Headphones", price: 149.99 },
{ name: "USB Cable", price: 12.99 },
{ name: "Mouse Pad", price: 9.99 },
];
const cheapest = minBy(cartItems, (item) => item.price);
// => { name: "Mouse Pad", price: 9.99 }
Get the nearest location
Find the closest point by distance calculation. Ideal for location services, delivery apps, or proximity searches.
const userPos = { lat: 48.8566, lng: 2.3522 };
const stores = [
{ name: "Store A", lat: 48.8698, lng: 2.3076 },
{ name: "Store B", lat: 48.8566, lng: 2.3629 },
{ name: "Store C", lat: 48.8867, lng: 2.3431 },
];
const nearest = minBy(stores, (s) =>
Math.hypot(s.lat - userPos.lat, s.lng - userPos.lng)
);
// => { name: "Store B", ... }
Find the oldest pending task
Identify tasks waiting the longest to prevent queue starvation. Useful for task management, ticketing, or job schedulers.
const tasks = [
{ id: "T1", title: "Fix bug", createdAt: new Date("2024-01-15") },
{ id: "T2", title: "Update docs", createdAt: new Date("2024-01-18") },
{ id: "T3", title: "Add feature", createdAt: new Date("2024-01-10") },
];
const oldest = minBy(tasks, (t) => t.createdAt.getTime());
// => { id: "T3", title: "Add feature", createdAt: Date("2024-01-10") }