groupBy
Groups the elements of an array into an object, keyed by the value of a specified property. Each key maps to an array of items that share that value.
Import
Section titled “Import”import { groupBy } from "1o1-utils";import { groupBy } from "1o1-utils/group-by";Signature
Section titled “Signature”function groupBy<T>({ array, key }: GroupByParams<T>): Record<string, T[]>Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| array | T[] | Yes | The array to group |
| key | keyof T | Yes | The property to group by |
Returns
Section titled “Returns”Record<string, T[]> — Object where keys are group values and values are arrays of matching items.
Examples
Section titled “Examples”const items = [ { name: "Alice", role: "admin" }, { name: "Bob", role: "user" }, { name: "Carol", role: "admin" },];
groupBy({ array: items, key: "role" });// => {// admin: [{ name: "Alice", role: "admin" }, { name: "Carol", role: "admin" }],// user: [{ name: "Bob", role: "user" }]// }Edge Cases
Section titled “Edge Cases”- Throws if
arrayis not an array. - Throws if
keyis undefined or null. - Groups are keyed by
String(value[key]).
Also known as
Section titled “Also known as”categorize, bucket, cluster, group array
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 groupBy to group transactions by category