JavaScript Map.groupBy()

Definition and usage

Map.groupBy() The method groups the elements of the object based on the string value returned by the callback function.

Map.groupBy() The method does not change the original 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 = Map.groupBy(fruits, myCallback);

Try it yourself

Note

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

Changes to any object will be reflected in the other object.

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.

Syntax

Map.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 group name of the element.

Return value

Type Description
Object Contains a Map object with grouped elements.

Browser support

Map.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