groupBy
Group array items by a key into an object of arrays.
#array
#utility
#grouping
export const groupBy = <T, K extends PropertyKey>( arr: readonly T[], getKey: (item: T) => K,): Record<K, T[]> => arr.reduce( (acc, item) => { const key = getKey(item); (acc[key] ||= []).push(item); return acc; }, {} as Record<K, T[]>, );
// Usageconst items = [ { type: 'fruit', name: 'apple' }, { type: 'vegetable', name: 'carrot' }, { type: 'fruit', name: 'banana' },];
groupBy(items, i => i.type);// {// fruit: [{ type: 'fruit', name: 'apple' }, { type: 'fruit', name: 'banana' }],// vegetable: [{ type: 'vegetable', name: 'carrot' }]// }