JavaScript

Group Array by Key

by @admin
10h ago
Apr 28, 2026
Public
Groups an array of objects into a map keyed by the result of a callback or property name. Uses Object.groupBy when available (ES2024) and falls back to a reduce implementation. Returns an object whose keys are the group names and values are arrays of matching items.
JavaScript
function groupBy(array, keyFn) {
  if (typeof Object.groupBy === 'function') {
    return Object.groupBy(array, keyFn);
  }
  return array.reduce((acc, item) => {
    const key = typeof keyFn === 'function' ? keyFn(item) : item[keyFn];
    (acc[key] ??= []).push(item);
    return acc;
  }, {});
}

// Usage
const people = [
  { name: 'Alice', dept: 'eng' },
  { name: 'Bob',   dept: 'design' },
  { name: 'Carol', dept: 'eng' },
];
console.log(groupBy(people, 'dept'));
// { eng: [Alice, Carol], design: [Bob] }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.