📂 Groups elements of an array based on a specified key or iteratee function.
Syntax
TypeScript
import { groupBy } from '@opentf/std'; groupBy<T>( arr: T[], key: ((val: T, index: number, arr: T[]) => string) | string ): Record<string, T[]>
Parameters
arr: The source array.key: A property name or a function that returns a string to use as the group key.
Returns
An object where keys are the result of the iteratee and values are arrays of elements that produced that key.
Examples
TypeScript
groupBy([]) //=> {} groupBy(["a"]) //=> { undefined: ["a"] } const products = [ { name: "apples", category: "fruits" }, { name: "oranges", category: "fruits" }, { name: "potatoes", category: "vegetables" }, ]; groupBy(products, "category") //=> { // fruits: [ // { name: "apples", category: "fruits" }, // { name: "oranges", category: "fruits" }, // ], // vegetables: [{ name: "potatoes", category: "vegetables" }], // }; groupBy([1, 2, 3, 4, 5, 6, 7, 8, 9], (v) => (v % 2 === 0 ? "Even" : "Odd")) //=> { // Even: [2, 4, 6, 8], // Odd: [1, 3, 5, 7, 9] // } groupBy(["one", "two", "three"], "length") //=> { // 3: ["one", "two"], // 5: ["three"], // }