diff --git a/src/array/groupBy.ts b/src/array/groupBy.ts index 4ef906d3a..9e4df427b 100644 --- a/src/array/groupBy.ts +++ b/src/array/groupBy.ts @@ -9,8 +9,9 @@ * @template K - The type of keys. * @param {T[]} arr - The array to group. * @param {(item: T) => K} getKeyFromItem - A function that generates a key from an element. - * @returns {Record} An object where each key is associated with an array of elements that - * share that key. + * @returns {Partial>} An object where each key is associated with an array of elements that + * share that key. If a specific key exists in K but at runtime no array element groups to that specific key, + * then that key maps to undefined rather than T[]. * * @example * const array = [ @@ -30,8 +31,11 @@ * // ] * // } */ -export function groupBy(arr: readonly T[], getKeyFromItem: (item: T) => K): Record { - const result = {} as Record; +export function groupBy( + arr: readonly T[], + getKeyFromItem: (item: T) => K +): Partial> { + const result = {} as Partial>; for (let i = 0; i < arr.length; i++) { const item = arr[i]; @@ -41,7 +45,7 @@ export function groupBy(arr: readonly T[], getKeyFromI result[key] = []; } - result[key].push(item); + result[key]!.push(item); } return result; diff --git a/src/compat/array/groupBy.ts b/src/compat/array/groupBy.ts index c120d915f..e8bde6de9 100644 --- a/src/compat/array/groupBy.ts +++ b/src/compat/array/groupBy.ts @@ -41,7 +41,7 @@ export function groupBy( export function groupBy( collection: T | null | undefined, iteratee?: ValueIteratee -): Record>; +): Partial>>; /** * Groups the elements of an array or object based on a provided key-generating function. @@ -58,8 +58,9 @@ export function groupBy( * - If a property name (string) is provided, that property of each element is used as the key. * - If a property-value pair (array) is provided, elements with matching property values are used. * - If a partial object is provided, elements with matching properties are used. - * @returns {Record} An object where each key is associated with an array of elements that - * share that key. + * @returns {Partial>} An object where each key is associated with an array of elements that + * share that key. If a specific key exists in K but at runtime no array element groups to that specific key, + * then that key maps to undefined rather than T[]. * * @example * // Using an array @@ -81,9 +82,9 @@ export function groupBy( | [keyof T, unknown] | PropertyKey | null -): Record { +): Partial> { if (source == null) { - return {} as Record; + return {} as Partial>; } const items = isArrayLike(source) ? Array.from(source) : Object.values(source);