← Back to libraryQuestion 162 of 468
🧩JavaScript CodingIntermediate

Group an Array of Objects by a Key

📌 Definition:

Given an array of objects, group them into an object keyed by a chosen field (e.g. group users by role).

📖 Detailed Explanation:

Use reduce to build an object whose keys are the group values and whose values are arrays. Modern engines also offer Object.groupBy, but reduce is universally supported.

💻 Solutions:
function groupBy(arr, key) {
  return arr.reduce((acc, item) => {
    const k = item[key];
    (acc[k] ||= []).push(item);
    return acc;
  }, {});
}
// Usage: groupBy(users, 'role') -> { admin: [...], qa: [...] }
🔑 Key Points:
  • reduce builds a keyed object of arrays
  • (acc[k] ||= []) initializes the bucket if absent
  • Object.groupBy is the newer built-in (check support)
  • O(n) single pass
🌍 Real-World Example:

Grouping powers report tables (orders by status, tests by suite) and is the JS equivalent of SQL GROUP BY for in-memory test data.

🎯 Scenario-Based Interview Question:

groupBy(items, 'type') throws 'Cannot read properties of undefined (reading push)'. What is the likely cause?