groupBy
A utility function to group an array of objects based on a specified key.> groupBy<T extends Record<string, any>, K extends keyof T>(array: T[], key: K): Record<T[K], T[]>
- array: An array of objects to be grouped.
- key: The key in the objects to group by.
- Returns: An object where each key corresponds to a unique value of the specified property in the objects, and the value is an array of objects with that property.
Example
import { groupBy } from "@explita/daily-toolset";
const data = [
{ category: "fruit", name: "apple" },
{ category: "fruit", name: "banana" },
{ category: "vegetable", name: "carrot" },
{ category: "vegetable", name: "lettuce" },
];
// Group data by the "category" property
const groupedData = groupBy(data, "category");
console.log(groupedData);
// Output:
// {
// fruit: [
// { category: "fruit", name: "apple" },
// { category: "fruit", name: "banana" },
// ],
// vegetable: [
// { category: "vegetable", name: "carrot" },
// { category: "vegetable", name: "lettuce" },
// ],
// }
const groupedByName = groupBy(data, "name");
console.log(groupedByName);
// Output:
// {
// apple: [{ category: "fruit", name: "apple" }],
// banana: [{ category: "fruit", name: "banana" }],
// carrot: [{ category: "vegetable", name: "carrot" }],
// lettuce: [{ category: "vegetable", name: "lettuce" }],
// }
Use Cases
- Organizing data for display, such as grouping items in a dropdown or table by category.
- Aggregating data based on specific properties for analysis or reporting.
- Creating nested structures for hierarchical data processing.