The Object.groupBy method lets you group items in an array into an object, based on a specific rule. This rule is set by a function that provides a key for each item. The method groups all items with the same key into arrays, with each key becoming a property in the object.
Syntax and Explanation
The syntax of the Object.groupBy method is straightforward:
Object.groupBy(iterableObject, callback);
iterableObject: An iterable objects(such as an Array) whose elements you want to group.
callback: A function that takes each element of the array and returns a key. The elements that produce the same key are grouped together.
The returned key can be a string or symbol, other returned values are converted to string.
Here’s a breakdown of how it works:
The callback function is applied to each element of the array.
The return value of the callback function is used as a key.
The elements that share the same key are grouped into an array.
The result is an object where each key corresponds to an array of grouped elements.