Code Snippets
/

Group an Array by a Key

Group an Array by a Key

Grouping records by a derived key is one of the most common data-shaping tasks in JavaScript: bucketing users by role, orders by status, logs by date. This snippet shows a portable `Map`-based helper, a plain-object variant, and the modern `Object.groupBy` API that landed in Node 22 and recent browsers. It also covers the multi-key composite-key trick for grouping by tuples like `[city, role]`.

JavaScript
Medium
4 snippets
arrays
utility
array-manipulation-patterns
hash-table

335 views

5

function groupBy(array, keyFn) {
    const groups = new Map();
    for (const item of array) {
        const key = keyFn(item);
        const bucket = groups.get(key);
        if (bucket) {
            bucket.push(item);
        } else {
            groups.set(key, [item]);
        }
    }
    return groups;
}

const users = [
    { name: 'Ada', role: 'admin' },
    { name: 'Bo', role: 'member' },
    { name: 'Cal', role: 'admin' },
    { name: 'Di', role: 'member' },
];

const byRole = groupBy(users, (u) => u.role);
console.log(byRole.get('admin').map((u) => u.name)); // ['Ada', 'Cal']
console.log(byRole.get('member').length);            // 2
console.log([...byRole.keys()]);                     // ['admin', 'member']

The function walks the input once and accumulates each item into a Map keyed by the result of keyFn(item). Using a Map instead of a plain object preserves insertion order, supports any key type (numbers, booleans, even objects), and avoids the __proto__ / constructor collision pitfalls of object-as-dictionary code. The whole pass is O(n) time and O(n) space, with one dictionary lookup and one push per element. Reach for this helper any time you need to bucket records before rendering a grouped list, computing per-group totals, or feeding a chart.