sortBy
Returns a new array sorted by a specified property. Supports ascending and descending order, as well as nested properties via dot notation.
Import
Section titled “Import”import { sortBy } from "1o1-utils";import { sortBy } from "1o1-utils/sort-by";Signature
Section titled “Signature”function sortBy<T>({ array, key, order = "asc" }: SortByParams<T>): T[]Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| array | T[] | Yes | The array to sort |
| key | keyof T | string | Yes | Property to sort by (supports dot notation for nested properties) |
| order | "asc" | "desc" | No | Sort direction (default: "asc") |
Returns
Section titled “Returns”T[] — A new sorted array (does not mutate the original).
Examples
Section titled “Examples”sortBy({ array: [{ age: 30 }, { age: 20 }], key: "age" });// => [{ age: 20 }, { age: 30 }]
sortBy({ array: [{ age: 30 }, { age: 20 }], key: "age", order: "desc" });// => [{ age: 30 }, { age: 20 }]
// Nested properties with dot notationsortBy({ array: users, key: "address.city" });Edge Cases
Section titled “Edge Cases”- Throws if
arrayis not an array. - Throws if
keyis undefined or null. - Supports both numeric and string comparisons.
- Supports nested keys via dot notation (e.g.,
"address.city").
Also known as
Section titled “Also known as”order by, sort array, arrange, rank
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use sortBy to sort a table by nested user.name field