Group by object identity
Classify records by a mutable object such as a department or account while retaining that object's identity.
JavaScript · Function
Map.groupBy() groups an iterable's elements by callback results and returns a Map from each group key to its matching elements. Unlike Object.groupBy(), it can use arbitrary object or primitive keys.
Map.groupBy() invokes the callback once for each item in an iterable. It uses each callback result as a Map key and stores the original items that produced that key in an array, preserving object identity rather than copying the items.
Map.groupBy(items, callbackFn)| Name | Type | Description |
|---|---|---|
items | Iterable | An iterable, such as an Array, whose elements are grouped. |
callbackFn | Function | A function called for each element; it returns the object or primitive used as that element's group key. It receives the element and its index. |
A Map whose keys are the groups and whose values are arrays containing the elements assigned to each group.
const products = [
{ name: "pen", category: "office" },
{ name: "apple", category: "food" },
{ name: "paper", category: "office" },
];
const byCategory = Map.groupBy(products, product => product.category);
console.log(byCategory.get("office").map(product => product.name));
// ["pen", "paper"]Creates a Map whose keys are category strings and whose values are arrays of the matching product objects.
Classify records by a mutable object such as a department or account while retaining that object's identity.
Partition values into categories such as status, type, or range while exposing groups through Map operations.
Group any iterable, including arrays and other iterable data sources, into arrays associated with computed keys.
Map.groupBy(items, callbackFn) accepts any iterable and returns a Map. The callback runs once per element, and its returned value becomes the key for an array containing all elements assigned to that group.
Follow-up: When is Object.groupBy() preferable? Use it when group keys can be represented as strings; Map.groupBy() supports arbitrary primitive or object keys.
The callback receives the current element and its index. Its result is compared as a Map key, so equal returned keys share one group.
Follow-up: Why can object keys be useful? A changing object can remain the grouping identity, whereas converting it to a string may lose that identity.
The method does not deep-copy elements. Each Map value is an array containing the original iterable elements that produced that key.
Follow-up: What happens if a grouped object changes later? The Map still contains the same object reference, so its internal changes are visible through the grouped result.
MapObject.groupBy()