It groups the elements of a given array according to the given key.
The key can be a string or a callback function that must return a string.
Syntax
import { groupBy } from '@opentf/std';
groupBy(arr: unknown[], key: string | x => string);
Examples
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"],
// }