Description
groupBy
takes an array of objects and a key
(string
), and returns an object where each distinct value of
that key
in the array becomes a property. The corresponding value is an array of all objects
from the input that share that key
value.
Code Byte
export const groupBy = <T extends Record<string, any>, K extends keyof T>(
arr: T[],
key: K
): Record<string, T[]> =>{
return arr.reduce((acc: Record<string, T[]>, obj: T) => {
const groupKey = String(obj[key]);
acc[groupKey] = acc[groupKey] || [];
acc[groupKey].push(obj);
return acc;
}, {});
}
Use cases:
- Data categorization: Group users by role, products by category, etc.
- Analytics aggregation: Bucket events by event type or date.
- UI rendering: Render sectioned lists grouped by a property (e.g., year, status).
- Batch processing: Partition items before processing each group separately.
Example usage:
import { groupBy } from './group-by.util';
interface User {
id: number;
name: string;
role: string;
}
const users: User[] = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'user' },
{ id: 3, name: 'Eve', role: 'admin' },
{ id: 4, name: 'Mallory', role: 'user' }
];
const usersByRole = groupBy(users, 'role');
console.log(usersByRole);
/*
{
admin: [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 3, name: 'Eve', role: 'admin' }
],
user: [
{ id: 2, name: 'Bob', role: 'user' },
{ id: 4, name: 'Mallory', role: 'user' }
]
}
*/