Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/array/groupBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<K, T[]>} An object where each key is associated with an array of elements that
* @returns {Record<K, [T, ...T[]]>} An object where each key is associated with a non-empty array of elements that
* share that key.
*
* @example
Expand All @@ -30,18 +30,21 @@
* // ]
* // }
*/
export function groupBy<T, K extends PropertyKey>(arr: readonly T[], getKeyFromItem: (item: T) => K): Record<K, T[]> {
const result = {} as Record<K, T[]>;
export function groupBy<T, K extends PropertyKey>(
arr: readonly T[],
getKeyFromItem: (item: T) => K
): Record<K, [T, ...T[]]> {
const result = {} as Record<K, [T, ...T[]]>;

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);
Comment on lines +44 to +46
Copy link
Author

@itsMapleLeaf itsMapleLeaf Jan 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I figured it would be a good idea to update the implementation to match the soundness of the return type

}

result[key].push(item);
}

return result;
Expand Down