GroupBy Function
Data Manipulation2 functions
Utility Overview
Details
Groups array items by a key selector function or property name
Category:Data Manipulation
Functions:groupBy, groupByProperty
Performance:
- Time: O(n) single pass through array - Space: O(n) for grouped result structure
Concepts:
array manipulationdata groupingfunctional programmingdata transformation
Implementation
groupBy
Time: O(n) | Space: O(n)
export function groupBy<T, K extends string | number | symbol>(
array: T[],
keySelector: (item: T) => K
): Record<K, T[]> {
if (!Array.isArray(array)) {
throw new Error('First argument must be an array');
}
if (typeof keySelector !== 'function') {
throw new Error('Second argument must be a function');
}
const result = {} as Record<K, T[]>;
for (const item of array) {
const key = keySelector(item);
if (!result[key]) {
result[key] = [];
}
result[key].push(item);
}
return result;
}Usage Examples
Group objects by property
const users = [
{ name: 'John', role: 'admin', age: 30 },
{ name: 'Jane', role: 'user', age: 25 },
{ name: 'Bob', role: 'admin', age: 35 }
];
const byRole = groupByProperty(users, 'role');
// { admin: [John, Bob], user: [Jane] }