Object.groupBy
Groups the elements of an iterable according to the string values returned by a provided callback function
Syntax
Object.groupBy(iterable, callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| iterable | Iterable<T> | An iterable whose elements will be grouped |
| callbackFn | (element, index) => string | Function that returns the group key for each element |
Return Value
A null-prototype object with properties for each group containing arrays of group members
Examples
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?.length); // 2const numbers = [1, 2, 3, 4, 5, 6];
const grouped = Object.groupBy(numbers, n =>
n % 2 === 0 ? 'even' : 'odd'
);
console.log(grouped.even); // [2, 4, 6]const words = ['hello', 'hi', 'world', 'web'];
const byLetter = Object.groupBy(words, w => w[0]);
console.log(byLetter.h); // ['hello', 'hi']Understanding Object.groupBy
The Object.groupBy method in JavaScript groups the elements of an iterable according to the string values returned by a provided callback function. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is Object.groupBy(iterable, callbackFn). It accepts 2 parameters: iterable, callbackFn. When called, it returns a null-prototype object with properties for each group containing arrays of group members. Understanding when and how to use groupBy() helps you write more expressive, readable code.
Common use cases for Object.groupBy include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-reduce, array-filter, array-map, enabling you to chain operations together for complex data manipulation pipelines.
Supported in Chrome 117+, Firefox 119+, Safari 17.4+, Edge 117+, and Node.js 21+.
Browser Compatibility
Supported in Chrome 117+, Firefox 119+, Safari 17.4+, Edge 117+, and Node.js 21+.
Related Methods
Array.prototype.reduceExecutes a user-supplied reducer callback function on each element of the array, passing in the return value from the calculation on the preceding element
Array.prototype.filterCreates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test implemented by the provided function
Array.prototype.mapCreates a new array populated with the results of calling a provided function on every element in the calling array
Object.fromEntriesTransforms a list of key-value pairs into an object
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.