The groupByToMap()
method executes callbackFn
once for each index of the array. The callback function returns a value indicating the group of the associated element. The values returned by callbackFn
are used as keys for the Map
returned by groupByToMap()
. Each key has an associated array containing all the elements for which the callback returned the same value.
The elements in the returned Map
and the original array are the same (not deep copies). Changing the internal structure of the elements will be reflected in both the original array and the returned Map
.
This method is useful when you need to group information that is related to a particular object that might potentially change over time. This is because even if the object is modified, it will continue to work as a key to the returned Map
. If you instead create a string representation for the object and use that as a grouping key in Array.prototype.groupBy()
, you must maintain the mapping between the original object and its representation as the object changes.
Note: To access the groups in the returned Map
, you must use the same object that was originally used as a key in the Map
(although you may modify its properties). You can't use another object that just happens to have the same name and properties.
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 groupByToMap()
, it will be used as the this
value inside each invocation of the callbackFn
. If it is not provided, then undefined
is used.