Skip to content

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 { groupBy } from "1o1-utils";
import { groupBy } from "1o1-utils/group-by";
function groupBy<T>({ array, key }: GroupByParams<T>): Record<string, T[]>
NameTypeRequiredDescription
arrayT[]YesThe array to group
keykeyof TYesThe property to group by

Record<string, T[]> — Object where keys are group values and values are arrays of matching items.

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" }]
// }
  • Throws if array is not an array.
  • Throws if key is undefined or null.
  • Groups are keyed by String(value[key]).

categorize, bucket, cluster, group array

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