JavaScript Object groupBy() method
groups elements of an object according to string values returned from a callback function

Object.groupBy() static method groups the elements of a given iterable according to the string values returned by a provided callback function.

syntax

Object.groupBy(items, callbackFn)

items An iterable (such as an Array) whose elements will be grouped.

callbackFn A function to execute for each element in the iterable. It should return a value that can get coerced into a property key (string or symbol) indicating the group of the current element. The function is called with the following arguments ↴

element The current element being processed.

index The index of the current element being processed.

The returned object has separate properties for each group, containing arrays with the elements in the group.

Object.groupBy() method should be used when group names can be represented by strings. If you need to group elements using a key that is some arbitrary value, use Map.groupBy() instead ↴

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

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

Object.groupBy() method groups elements of an object according to string values returned from a callback function.

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

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

Changes will be reflected in both the original and in the returned object.

myObject

// create an object

const inventory = [

{ name: "Broccoli", type: "vegetables", quantity: 7 },

{ name: "Apples", type: "fruit", quantity: 0 },

{ name: "Cauliflower", type: "vegetables", quantity: 8 },

{ name: "Almonds", type: "nuts", quantity: 16 },

{ name: "Pears", type: "fruit", quantity: 7 },

{ name: "Walnuts", type: "nuts", quantity: 15 },

]

syntax description
group elements of inventory object according to string values returned from callback function
Object.groupBy(items, callbackFn)