Aller au contenu principal

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.

DEPRECATED

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