Partition records by a string property
You have records with a stable categorical field such as type, status, or department.
JavaScript · Function
Object.groupBy() groups an iterable's elements by keys returned from a callback. It returns a null-prototype object whose properties contain arrays of the original elements for each group.
Object.groupBy() consumes an iterable and invokes the callback for each element with the element and its index. Each callback result becomes a property key, and the returned null-prototype object stores an array of the original elements under every distinct key.
Object.groupBy(items, callbackFn)| Name | Type | Description |
|---|---|---|
items | Iterable | An iterable, such as an Array, whose elements will be grouped. |
callbackFn | Function | A function called for each element; it returns a value coerced to a property key indicating that element's group. |
A null-prototype object whose group properties each contain an array of the associated original elements.
const inventory = [
{ name: "asparagus", type: "vegetables" },
{ name: "bananas", type: "fruit" },
{ name: "goat", type: "meat" },
{ name: "cherries", type: "fruit" },
];
const result = Object.groupBy(inventory, ({ type }) => type);
console.log(result.fruit.map(({ name }) => name)); // ["bananas", "cherries"]The callback returns each item's type, so the result has one null-prototype property per type containing the matching original elements.
You have records with a stable categorical field such as type, status, or department.
You need to classify iterable values with a computed label.
You want grouped data represented as ordinary object properties for property-key access.
It groups an iterable by callback-derived property keys and returns a null-prototype object. Each property contains an array of the elements whose callback result produced that key.
Follow-up: How would you group by an object key? Use Map.groupBy(), because Object.groupBy() converts keys to property keys while Map.groupBy() supports arbitrary values.
The callback runs once per iterable element and receives the current element and its index. Its return value identifies the group; values that are not strings or symbols are coerced to strings.
Follow-up: What happens to the callback's third argument? The MDN page documents the element and index arguments for Object.groupBy(), so code should not rely on a documented array argument.
Use Object.groupBy() when group names can be represented by strings or symbols. Use Map.groupBy() when the grouping key must be an arbitrary value, such as an object.
Follow-up: Why can converting an object key to a string be problematic? Different objects can share a string representation, and changes to an object may make that representation stale.
Map.groupBy()ObjectArray.prototype.reduce()