Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Collections

Map.groupBy()

Reference for Map.groupBy(): group the items of an iterable into a Map of arrays using a callback, with any key type, plus how it differs from Object.groupBy().

Map.groupBy(items, callback) walks an iterable, calls your callback for each item, and collects the items into a new Map. Each key is whatever the callback returned, and each value is an array of the items that produced that key, in their original order.

It is the grouping tool to choose when keys are not strings (numbers, booleans, objects) or when you want the result to keep first-seen order and expose size. For string keys in a plain object, see Object.groupBy().

JavaScript
const groups = Map.groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? "even" : "odd"));
// Map { "odd" => [1, 3, 5], "even" => [2, 4] }

Try it

JS Grouping by a computed key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Any key type and the index argument

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Map.groupBy(items, callbackFn)
Name Description
items An iterable (array, string, set, generator...) whose items are grouped.
callbackFn Called as callbackFn(item, index) for each item. Its return value is the group key.

Return value: a new Map whose keys are the callback results (in order of first appearance) and whose values are arrays of the matching items.

Exceptions: a TypeError if items is null, undefined or not iterable, or if callbackFn is not a function. Errors thrown by the callback propagate.

Usage notes

  • Keys use "same value zero". Equal primitives share a group; objects are separate groups unless they are the very same object. Return a string or number from the callback when you want content-based groups.
  • The input is not changed. The function builds a new map and leaves the source untouched.
  • Group arrays are fresh arrays, but the items inside them are the original references, not copies.
  • Only groups that occur exist. Look-ups for keys with no items return undefined, so use map.get(key) ?? [] when you need an empty array.
  • Compared with Object.groupBy(). The object version converts keys to strings (property keys) and returns an object with no prototype. Use Map.groupBy() for non-string keys, for guaranteed order, or when keys could collide with property names.
  • Not the same as reduce(). A hand-written reduce() grouping still works in older environments, but groupBy states the intent and avoids the bookkeeping.
  • It takes any iterable, so Map.groupBy(new Set(items), fn) and generators work, not only arrays.

Browser support

Map.groupBy() is a recent addition and is available in current versions of the major browsers and Node.js, but not in older ones. Check a compatibility table before depending on it.