Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Object.groupBy

Groups the elements of an array by a key.

Available since: ES2024

Syntax

Object.groupBy(items, callbackFn)

Parameters

ParameterTypeDescription
itemsIterableAn array or another iterable.
callbackFnFunctionA function that returns the group key for an element.

Return value

objectAn object where each key is a group and the value is an array of its elements.

Examples

Even and odd numbers:

const groups = Object.groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? 'even' : 'odd'));
 
console.log(groups.even.join(', '));
console.log(groups.odd.join(', '));

Output:

2, 4
1, 3, 5

Products by category:

const products = [
  { name: 'Apple', type: 'fruit' },
  { name: 'Carrot', type: 'vegetable' },
  { name: 'Pear', type: 'fruit' },
];
const byType = Object.groupBy(products, (product) => product.type);
 
console.log(byType.fruit.map((p) => p.name).join(', '));
console.log(Object.keys(byType));

Output:

Apple, Pear
[
  "fruit",
  "vegetable"
]

Notes

If the group keys are not strings (objects, for example), use Map.groupBy(). Before this method existed grouping was written with reduce().

See also

Related recipes

In the tutorial

Thanks for reading!

Donate to the site — we work hard for you.