JavaScript - group() method

revision:


Category : array

This is an experimental technology

The group() method groups the elements of the calling array according to the string values returned by a provided testing function. The returned object has separate properties for each group, containing arrays with the elements in the group.

This 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 Array.prototype.groupToMap() instead.

Syntax :

        group(callbackFn)
        group(callbackFn, thisArg)        
    
    

Parameters:

callbackFn : required. A function to execute for each element in the array. 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 in the array.
index : the index of the current element being processed in the array.
array : the array group() was called upon.

thisArg : optional. A value to use as "this" when executing callbackFn.

Examples:

            const inventory = [
                { name: "asparagus", type: "vegetables", quantity: 5 },
                { name: "bananas", type: "fruit", quantity: 0 },
                { name: "goat", type: "meat", quantity: 23 },
                { name: "cherries", type: "fruit", quantity: 5 },
                { name: "fish", type: "meat", quantity: 22 },
            ];
            const result = inventory.group(({ type }) => type);
           
            /* Result is:
                {
                vegetables: [
                    { name: 'asparagus', type: 'vegetables', quantity: 5 },
                ],
                fruit: [
                    { name: "bananas", type: "fruit", quantity: 0 },
                    { name: "cherries", type: "fruit", quantity: 5 }
                ],
                meat: [
                    { name: "goat", type: "meat", quantity: 23 },
                    { name: "fish", type: "meat", quantity: 22 }
                ]
                }
                */
        

Practical examples

example:

code:
                    
                

example:

code:
                    
                

example:

code: