JavaScriptEasy
Group an array of objects by key
Use Object.groupBy(items, item => key) (or Map.groupBy for non-string keys) in modern JavaScript; in interviews, implement it with a single reduce or loop that pushes each item into the array for its key.
Built-ins (ES2024)
Object.groupBy(iterable, fn)returns a null-prototype object:{ [key]: items[] }. Keys are converted to strings.Map.groupBy(iterable, fn)returns aMap, so keys can be objects, numbers or dates without string conversion. Both preserve the original order within each group.
Manual implementation
One pass over the data, O(n):
const groups = {};
for (const item of items) (groups[key(item)] ??= []).push(item);
Use Object.create(null) (or a Map) so a key like "constructor" or "__proto__" cannot collide with inherited properties.
Useful variations
- Group by a property name or by a computed key (first letter, year, price range).
- Group and aggregate: count, sum or average per group.
- Nested grouping: by year, then by month.
- Count only: when you only need counts, accumulate numbers instead of arrays.
Where it comes up
Rendering sectioned lists, building charts, reports by category, and organising API results.
Code example
js
1const orders = [2 { id: 1, customer: "Ada", status: "paid", total: 120, date: "2026-01-05" },3 { id: 2, customer: "Linus", status: "pending", total: 80, date: "2026-01-20" },4 { id: 3, customer: "Ada", status: "paid", total: 45, date: "2026-02-02" },5 { id: 4, customer: "Grace", status: "refunded", total: 60, date: "2026-02-14" },6];78// Built-in (ES2024)9const byStatus = Object.groupBy(orders, (o) => o.status);10console.log(Object.keys(byStatus), byStatus.paid.map((o) => o.id)); // ["paid", "pending", "refunded"] [1, 3]1112// Manual implementation with a safe, prototype-free object13function groupBy(items, keyOrFn) {14 const getKey = typeof keyOrFn === "function" ? keyOrFn : (item) => item[keyOrFn];15 const groups = Object.create(null);16 for (const item of items) (groups[getKey(item)] ??= []).push(item);17 return groups;18}19console.log(groupBy(orders, "customer").Ada.length); // 22021// Computed key: by month22console.log(Object.keys(groupBy(orders, (o) => o.date.slice(0, 7)))); // ["2026-01", "2026-02"]2324// Group and aggregate: revenue per customer25const revenue = Object.fromEntries(26 Object.entries(groupBy(orders, "customer")).map(([name, list]) => [name, list.reduce((s, o) => s + o.total, 0)])27);28console.log(revenue); // { Ada: 165, Linus: 80, Grace: 60 }2930// Map.groupBy keeps non-string keys31const bySize = Map.groupBy(orders, (o) => (o.total >= 100 ? "large" : "small"));32console.log([...bySize.keys()]); // ["large", "small"]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.