Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Map.groupBy() and array grouping

Reference for JavaScript Map.groupBy(): group the items of an array or any iterable into a Map by a key function, and how it differs from Object.groupBy().

Map.groupBy() is a static method that sorts the items of an iterable (usually an array) into groups. You pass the items and a callback that returns a key for each item. The result is a Map whose keys are those returned keys and whose values are arrays of the items that got that key.

Because the result is a Map, keys can be any value: strings, numbers, objects or booleans. If you only need string keys and prefer a plain object, there is a sibling method, Object.groupBy(). There is no Array.prototype.groupBy(); grouping lives on the constructors.

JavaScript
const groups = Map.groupBy([1, 2, 3, 4], (n) => n % 2 === 0);
// Map { false => [1, 3], true => [2, 4] }

Try it

JS Group words by length

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

No output.

JS Map versus object keys

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

No output.

Syntax

JavaScript
Map.groupBy(items, callbackFn)
Name Description
items An iterable, such as an array, string, Set or generator.
callbackFn A function called once per item as callbackFn(item, index). It returns the key of the group the item belongs to.

Return value: a new Map. Each key is a value returned by the callback; each value is an array of the items that produced that key, in the original order. Groups appear in the order their keys were first seen.

Exceptions: TypeError if items is not iterable or callbackFn is not a function.

Usage notes

  • Keys follow Map rules. They are compared with SameValueZero, so NaN groups together and 0 and -0 are the same key. Two different objects are two different keys, even if they look alike.
  • Items are not copied. The group arrays contain the original values (or object references).
  • Missing group. get() returns undefined for a key nobody produced; check before using the result, for example map.get(key) ?? [].
  • Object.groupBy() returns a null-prototype object whose keys are converted to strings (or symbols). Use it when you want to read results with dot or bracket access or serialize them to JSON; use Map.groupBy() when keys are not strings.
  • Non-mutating. The input is never changed, and the callback should not change it either.
  • Before groupBy, the usual pattern was a reduce() or a loop that creates the group array on first use. The new methods replace that boilerplate.
  • Counting instead of collecting. If you only need counts, loop once and keep a Map of numbers; building every group array wastes memory.

Browser support

Map.groupBy() and Object.groupBy() are recent additions. They work in current browsers and recent Node.js versions, but check a compatibility table before relying on them for older environments.