mirror of
https://github.com/toss/es-toolkit.git
synced 2024-11-28 03:34:26 +03:00
1eada4d85d
* feat(orderBy): add orderBy function * feat(orderBy): add orderBy test code * feat(orderBy): add orderBy bench * feat(orderBy): add orderBy function docs * feat(orderBy): add orderBy vitepress docs * fix: test function & add the extend orders feature * Update src/array/orderBy.ts --------- Co-authored-by: Sojin Park <raon0211@gmail.com> Co-authored-by: Sojin Park <raon0211@toss.im>
1.2 KiB
1.2 KiB
orderBy
Sorts an array of objects based on multiple properties and their corresponding order directions.
This function takes an array of objects, an array of keys to sort by, and an array of order directions. It returns the sorted array, ordering by each key according to its corresponding direction ('asc' for ascending or 'desc' for descending). If values for a key are equal, it moves to the next key to determine the order.
Signature
function orderBy<T>(collection: T[], keys: Array<keyof T>, orders: Order[]): T[];
Parameters
collection
(T[]
): The array of objects to be sorted.keys
(Array<keyof T>
): An array of keys (properties) by which to sort.orders
(Order[]
): An array of order directions ('asc' for ascending or 'desc' for descending).
Returns
(T[]
) The sorted array.
Examples
const users = [
{ user: 'fred', age: 48 },
{ user: 'barney', age: 34 },
{ user: 'fred', age: 40 },
{ user: 'barney', age: 36 },
];
const result = orderBy(users, ['user', 'age'], ['asc', 'desc']);
// result will be:
// [
// { user: 'barney', age: 36 },
// { user: 'barney', age: 34 },
// { user: 'fred', age: 48 },
// { user: 'fred', age: 40 },
// ]