The groupToMap()
method is an iterative method. It calls a provided callbackFn
function once for each element in an 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 groupToMap()
. Each key has an associated array containing all the elements for which the callback returned the same value.
callbackFn
is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined
.
The groupToMap()
method is a copying method. It does not alter this
but instead returns a map of arrays that contains the same elements as the ones from the original array. However, the function provided as callbackFn
can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn
. Therefore:
-
callbackFn
will not visit any elements added beyond the array's initial length when the call to groupToMap()
began. - Changes to already-visited indexes do not cause
callbackFn
to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by
callbackFn
, its value passed to the callbackFn
will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined
.
Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).
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
.
The groupToMap()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
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.group()
, 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.