Advertisement
Advanced JavaScript, Map, Set, WeakMap & WeakSet

How would you group an array of objects by a property using Map, and how does the newer Object.groupBy() compare?

Short answer

Iterate the array, computing a key for each item, and push it into a Map bucket for that key (creating the bucket on first use) — this preserves object references as keys if needed.

Save JavaScript mock interview
Advertisement
AModel answer
Iterate the array, computing a key for each item, and push it into a Map bucket for that key (creating the bucket on first use) — this preserves object references as keys if needed. The newer Object.groupBy() (and Map.groupBy()) built-ins do this in one call, returning a null-prototype object or Map respectively.
const byRole = new Map();
for (const user of users) {
  const key = user.role;
  if (!byRole.has(key)) byRole.set(key, []);
  byRole.get(key).push(user);
}

// Newer built-in:
const grouped = Map.groupBy(users, u => u.role);
Real-world example
Grouping a flat list of orders by customer ID before rendering them as separate sections in a UI.
Likely follow-ups
  • What browser/runtime support considerations apply to Object.groupBy() and Map.groupBy()?
Related topics