Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Map.groupBy()

ES2024 brought the Map.groupBy() method to JavaScript.

This method organizes the elements of an object according to string values generated by a callback function.

Additionally, the Map.groupBy() method does not alter the original object.

Example

// Create an Array
const fruits = [
  {name:“apples”, quantity:300},
  {name:“bananas”, quantity:500},
  {name:“oranges”, quantity:200},
  {name:“kiwi”, quantity:150}
];

// Callback function to Group Elements
function myCallback({ quantity }) {
  return quantity > 200 ? “ok” : “low”;
}

// Group by Quantity
const result = Map.groupBy(fruits, myCallback);

Browser Support

The Map.groupBy() method is a feature introduced in ES2024.

It is supported in new browsers as of March 2024.

js 2

Object.groupBy() vs Map.groupBy()

The distinction between Object.groupBy() and Map.groupBy() is:

Object.groupBy() organizes elements into a JavaScript object, while Map.groupBy() organizes elements into a Map object.