Skip to content

sortBy

Returns a new array sorted by a specified property. Supports ascending and descending order, as well as nested properties via dot notation.

import { sortBy } from "1o1-utils";
import { sortBy } from "1o1-utils/sort-by";
function sortBy<T>({ array, key, order = "asc" }: SortByParams<T>): T[]
NameTypeRequiredDescription
arrayT[]YesThe array to sort
keykeyof T | stringYesProperty to sort by (supports dot notation for nested properties)
order"asc" | "desc"NoSort direction (default: "asc")

T[] — A new sorted array (does not mutate the original).

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 notation
sortBy({ array: users, key: "address.city" });
  • Throws if array is not an array.
  • Throws if key is undefined or null.
  • Supports both numeric and string comparisons.
  • Supports nested keys via dot notation (e.g., "address.city").

order by, sort array, arrange, rank

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