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
Examples
const items = [
{ name: 'Alice', dept: 'eng' },
{ name: 'Bob', dept: 'sales' },
{ name: 'Charlie', dept: 'eng' },
];
const grouped = Object.groupBy(items, i => i.dept);
console.log(grouped.eng?.length); // 2const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const grouped = Object.groupBy(numbers, n =>
n <= 3 ? 'low' : n <= 7 ? 'mid' : 'high'
);
console.log(grouped.mid); // [4, 5, 6, 7]const words = ['apple', 'banana', 'avocado', 'blueberry'];
const byFirst = Object.groupBy(words, w => w[0]);
console.log(byFirst.a); // ['apple', 'avocado']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 Object object and is one of the most widely used methods for working with object 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. 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-groupby, array-reduce, object-fromentries, 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
Object.groupByGroups the elements of an iterable according to the string values returned by a provided callback function
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
Object.fromEntriesTransforms a list of key-value pairs into an object
More Object Methods
Other methods in the Object object
Related Tools
More Object Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.