groupBy walks an array once and bins each item under the string form of item[key]. Useful for building lookup tables, rendering grouped lists, or reducing flat data to a categorized shape.
export function groupBy<T>(arr: T[], key: keyof T): Record<string, T[]> {
return arr.reduce<Record<string, T[]>>((acc, item) => {
const group = String(item[key]);
if (!acc[group]) acc[group] = [];
acc[group].push(item);
return acc;
}, {});
}
Notes
- The key value is coerced via
String(...)so numeric and boolean fields work, but at the cost of losing their original type as a record key. - For the standard-library equivalent on modern runtimes, see
Object.groupBy(ES2024).