Browse topics

Object.groupBy and Map.groupBy

Version
es2025
Since
es2024
Review
Draft

Summary#

Object.groupBy splits an iterable into arrays keyed by the property key your callback returns. Map.groupBy keeps each returned value as a Map key.

Syntax#

js
const byName = Object.groupBy(items, (item, index) => propertyKey);
const byValue = Map.groupBy(items, (item, index) => key);

Example#

js
const tasks = [
  { title: "lint", state: "done" },
  { title: "test", state: "open" },
  { title: "build", state: "done" },
];

const groups = Object.groupBy(tasks, (task) => task.state);
console.log(groups.done?.map((task) => task.title).join(","));
console.log(groups.blocked, Object.getPrototypeOf(groups));

const byLength = Map.groupBy(tasks, (task) => task.title.length);
console.log(byLength.get(4)?.length);

Expected output#

Text
lint,build
undefined null
2

Common mistakes#

The object from Object.groupBy has no prototype, so calling groups.hasOwnProperty(key) fails. Use Object.hasOwn(groups, key). A group with no members is absent. Use Map.groupBy when keys must remain objects or numbers.

Version applicability#

ES2024 added both methods. On older runtimes, build groups in a loop using Object.create(null) for property keys or a Map to retain key types.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0