Array

Object.groupBy

Groups the elements of an iterable according to the string values returned by a provided callback function

Syntax

JavaScript
Object.groupBy(iterable, callbackFn)

Parameters

ParameterTypeDescription
iterableIterable<T>An iterable whose elements will be grouped
callbackFn(element, index) => stringFunction 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

Basic Usage
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); // 2
Practical Example
const 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]
Advanced Usage
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

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.