Group an array of objects by a key
Build an object of arrays keyed by a property or computed value, using Object.groupBy or a reduce fallback.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function groupBy(items, keyFn) {
const groups = Object.create(null);
for (const item of items) {
const key = keyFn(item);
(groups[key] ??= []).push(item);
}
return groups;
}Example / expected output
groupBy([{ n: "a", t: 1 }, { n: "b", t: 2 }, { n: "c", t: 1 }], (x) => x.t)
// { 1: [{n:"a",t:1}, {n:"c",t:1}], 2: [{n:"b",t:2}] }How it works
Modern runtimes (Node 21+, current browsers) ship Object.groupBy. The fallback below works anywhere and keeps insertion order within each group. The result uses a null prototype so a key like "__proto__" from user data cannot pollute anything.
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.

