Generic groupBy with key inference
Group an array into a Record by a property or function while keeping the item type.
- TypeScript
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
function groupBy<T, K extends string | number>(
items: readonly T[],
getKey: (item: T) => K,
): Partial<Record<K, T[]>> {
const result: Partial<Record<K, T[]>> = {};
for (const item of items) {
const key = getKey(item);
(result[key] ??= []).push(item);
}
return result;
}Example / expected output
const byRole = groupBy(users, (u) => u.role);
// Partial<Record<"admin" | "member", User[]>>How it works
The key function decides the group name, and the return type is a partial record because not every possible key necessarily appears. Object.groupBy exists in newer runtimes, but this version works everywhere and is easy to extend.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.

