The groupBy()
method executes the callbackFn
function once for each index of the array, returning a string (or value that can be coerced to a string) indicating the group of the element. A new property and array is created in the result object for each unique group name that is returned by the callback. Each element is added to the array in the property that corresponds to its group.
Note that the returned object references the same elements as the original array (not deep copies). Changing the internal structure of these elements will be reflected in both the original array and the returned object.
callbackFn
is called with the value of the current element, the current index, and the array itself. While groups often depend only on the current element, it is possible to implement grouping strategies based on the values of other elements in the array.
callbackFn
is invoked for every index of the array, not just those with assigned values. This means it may be less efficient for sparse arrays, compared to methods that only visit assigned values.
If a thisArg
parameter is provided to groupBy()
, it will be used as the this
value inside each invocation of the callbackFn
. If it is not provided, then undefined
is used.