Given an array of objects, group them into an object keyed by a chosen field (e.g. group users by role).
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.
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: [...] }Grouping powers report tables (orders by status, tests by suite) and is the JS equivalent of SQL GROUP BY for in-memory test data.
groupBy(items, 'type') throws 'Cannot read properties of undefined (reading push)'. What is the likely cause?