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.
// 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); |
The Map.groupBy() method is a feature introduced in ES2024.
It is supported in new browsers as of March 2024.
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.