JavaScript Object.groupBy()

Definition and usage

Object.groupBy() The method groups the elements of the object according to the string value returned by the callback function.

Object.groupBy() The method does not change the original object.

Note

The elements in the original object and the returned object are the same.

Changes to either object will reflect in the other.

The difference between Object.groupBy() and Map.groupBy()

Object.groupBy() and Map.groupBy() The difference is:

Object.groupBy() Group elements into a JavaScript object.

Map.groupBy() Group elements into a Map object.

Instance

// Create an array
const fruits = [
  {name: "apples", quantity: 300},
  {name: "bananas", quantity: 500},
  {name: "oranges", quantity: 200},
  {name: "kiwi", quantity: 150}
];
// Callback function for grouping elements
function myCallback({ quantity }) {
  return quantity > 200 ? "ok" : "low";
}
// Group by quantity
const result = Object.groupBy(fruits, myCallback);

Try it yourself

Syntax

Object.groupBy(iterable, callback)

Parameter

Parameter Description
iterable Required. An iterable array or Map.
callback

Required. The function executed for each element.

This function should return the grouping name of the element.

Return value

Type Description
Iterator Contains an iterable object with grouping elements.

Browser support

Object.groupBy() It is a feature of ES2024.

Starting from March 2024, all modern browsers fully support:

Chrome Edge Firefox Safari Opera
Chrome 117 Edge 117 Firefox 119 Safari 17.4 Opera 103
September 2023 September 2023 October 2023 October 2024 May 2023