diff --git a/src/array/groupBy.ts b/src/array/groupBy.ts index 4ef906d3a..4c0bfea8f 100644 --- a/src/array/groupBy.ts +++ b/src/array/groupBy.ts @@ -9,7 +9,7 @@ * @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 + * @returns {Record} An object where each key is associated with a non-empty array of elements that * share that key. * * @example @@ -30,18 +30,21 @@ * // ] * // } */ -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 +): Record { + const result = {} as Record; for (let i = 0; i < arr.length; i++) { const item = arr[i]; const key = getKeyFromItem(item); if (!Object.hasOwn(result, key)) { - result[key] = []; + result[key] = [item]; + } else { + result[key].push(item); } - - result[key].push(item); } return result;