maxBy()
maxBy<
T>(array,iteratee):T
maxBy<
T>(array,iteratee):T|undefined
Returns the element with the maximum 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 maximum value, or undefined if empty.
Sinceโ
2.0.0
Performanceโ
O(n) time, O(1) space.
Also known asโ
max (Radashi) ยท maxBy (Lodash, es-toolkit, Remeda, Ramda) ยท โ (Effect, Modern Dash, Antfu)
Exampleโ
maxBy([{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }] as const, (u) => u.age);
// => { name: 'Jane', age: 30 }
maxBy([{ name: 'John', age: 25 }, { name: 'Jane', age: 30 }], (u) => u.age);
// => { name: 'Jane', age: 30 }
maxBy([], (x) => x);
// => undefined
How it works?โ
Finds the element with the maximum value computed by iteratee.
Use Casesโ
Find the highest-earning employee ๐โ
Identify top performers by a numeric field. Perfect for HR analytics, leaderboards, or compensation reports.
const employees = [
{ name: "Alice", salary: 95000 },
{ name: "Bob", salary: 78000 },
{ name: "Charlie", salary: 120000 },
];
const highestPaid = maxBy(employees, (e) => e.salary);
// => { name: "Charlie", salary: 120000 }
Get the most recent entryโ
Find the latest item based on timestamp or date. Ideal for activity feeds, audit logs, or "last updated" features.
const orders = [
{ id: "ORD-001", createdAt: new Date("2024-01-10") },
{ id: "ORD-002", createdAt: new Date("2024-01-15") },
{ id: "ORD-003", createdAt: new Date("2024-01-12") },
];
const mostRecent = maxBy(orders, (o) => o.createdAt.getTime());
// => { id: "ORD-002", createdAt: Date("2024-01-15") }
Select the best-rated productโ
Find top-rated items for recommendations or featured sections. Useful for e-commerce, reviews, or content curation.
const products = [
{ name: "ProBook", rating: 4.5 },
{ name: "UltraSlim", rating: 4.8 },
{ name: "GameMaster", rating: 4.6 },
];
const topRated = maxBy(products, (p) => p.rating);
// => { name: "UltraSlim", rating: 4.8 }