Typescript6/5/2026
Group Array Of Objects By Key
Gom nhóm một mảng các đối tượng (objects) thành một object lớn dựa trên một thuộc tính (key) cụ thể.
groupBy.ts
export function groupBy<T, K extends keyof T>(
array: T[],
key: K
): Record<string, T[]> {
return array.reduce((result, currentValue) => {
// Ép kiểu thuộc tính thành string để làm key cho object
const groupKey = String(currentValue[key]);
// Nếu chưa có nhóm này, tạo mảng rỗng
if (!result[groupKey]) {
result[groupKey] = [];
}
// Push item vào nhóm tương ứng
result[groupKey].push(currentValue);
return result;
}, {} as Record<string, T[]>);
}
// Cách dùng:
// const users = [{ role: 'admin', name: 'A' }, { role: 'user', name: 'B' }, { role: 'admin', name: 'C' }];
// const groupedUsers = groupBy(users, 'role');
// Kết quả: { admin: [{...A}, {...C}], user: [{...B}] }