sortBy()
sortBy<
T>(collection,iteratee):T[]
Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru an iteratee.
Use array.toSorted() with custom comparator directly instead.
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
collection: Record<string, T> | T[]โ
The collection to iterate over.
iteratee: (value, indexOrKey?, collection?) => string | numberโ
The iteratee invoked per element.
Returns: T[]โ
The new sorted array.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
sort (Radashi, Modern Dash) ยท sortBy (Lodash, es-toolkit, Remeda, Ramda, Effect) ยท โ (Antfu)
Exampleโ
const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 20 }
];
// โ Deprecated approach
const sortedByAge = sortBy(users, user => user.age);
console.log(sortedByAge);
// [{ name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Jane', age: 30 }]
// โ
Recommended approach
const sortedByAgeNative = [...users].sort((a, b) => a.age - b.age);
console.log(sortedByAgeNative);
// [{ name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Jane', age: 30 }]
// โ
Modern approach with ES2023
const sortedModern = users.toSorted((a, b) => a.age - b.age);
console.log(sortedModern);
// [{ name: 'Bob', age: 20 }, { name: 'John', age: 25 }, { name: 'Jane', age: 30 }]
How it works?โ
Creates an array sorted by iteratees.
Deprecated: Use array.toSorted() (ES2023) or [...arr].sort().
Native Equivalentโ
// โ sortBy(arr, 'age')
// โ
[...arr].sort((a, b) => a.age - b.age)
// โ
arr.toSorted((a, b) => a.age - b.age) // ES2023
Use Casesโ
Sort objects by property ๐โ
Sort an array of objects by a specific property.
const users = [{ name: "Charlie" }, { name: "Alice" }, { name: "Bob" }];
users.toSorted((a, b) => a.name.localeCompare(b.name));
// => [{ name: "Alice" }, { name: "Bob" }, { name: "Charlie" }]
Order by numeric valueโ
Sort items by a numeric property.
const products = [{ price: 30 }, { price: 10 }, { price: 20 }];
products.toSorted((a, b) => a.price - b.price);
// => [{ price: 10 }, { price: 20 }, { price: 30 }]
Sort by dateโ
Order items chronologically.
const events = [{ date: new Date("2024-03") }, { date: new Date("2024-01") }];
events.toSorted((a, b) => a.date - b.date);
Sort with multiple criteriaโ
Sort by a primary key and break ties with a secondary key. Very common for file explorers, task lists, and any sortable table.
const files = [
{ name: "readme.md", modified: new Date("2025-06-01") },
{ name: "index.ts", modified: new Date("2025-06-10") },
{ name: "readme.md", modified: new Date("2025-05-15") },
{ name: "config.json", modified: new Date("2025-06-10") },
];
const sorted = sortBy(files, [(f) => f.name, (f) => -f.modified.getTime()]);
// => config.json (Jun 10), index.ts (Jun 10), readme.md (Jun 1), readme.md (May 15)
// Same name โ most recent first