Object.groupBy()

Groups elements by a key returned from a function.

Returns
An object with no prototype, with an array of elements in each group.
Changes the original
No
On this page

Example

#
JavaScript
const students = [
  { name: 'Emma', level: 'advanced' },
  { name: 'Jack', level: 'beginner' },
  { name: 'Mia', level: 'advanced' }
]

const byLevel = Object.groupBy(students, (s) => s.level)
console.log(byLevel.advanced.map((s) => s.name))
console.log(Object.keys(byLevel))
Console
['Emma', 'Mia']
['advanced', 'beginner']

Definition and usage

#

The Object.groupBy(items, callbackFn) method walks over the elements and calls the function for each one; the function returns the name of the group. The result is an object where each group is an array of the matching elements.

It replaces a popular but less readable pattern built on reduce(). Grouping tasks by status, students by level, or products by category is now one line.

The returned object has no prototype, so it doesn’t have methods like hasOwnProperty. If the group keys aren’t strings (for example, objects), use Map.groupBy().

Syntax

#
Syntax
Object.groupBy(items, callbackFn)

Parameters

#
  • items

    iterable object

    The elements to group, for example an array.
  • callbackFn

    function (element, index)

    The function that returns a group name for an element.

Browser support

#

Newly available · since 2024

Works in the current versions of all major browsers. Older versions may not support it.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • For older browsers, you can get the same result with reduce() or a small polyfill.
  • To group by objects or numbers without converting them to text, use Map.groupBy().

Related entries

#

Spotted a mistake or missing an example? Write to us.