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 }