diff --git a/packages/collection/__tests__/collection.test.ts b/packages/collection/__tests__/collection.test.ts index eaff8418b..3f0af6514 100644 --- a/packages/collection/__tests__/collection.test.ts +++ b/packages/collection/__tests__/collection.test.ts @@ -944,6 +944,29 @@ describe('union() tests', () => { }); }); +describe('groupBy() tests', () => { + test('returns a collection of grouped items', () => { + const items = [ + { name: 'Alice', age: 20 }, + { name: 'Bob', age: 20 }, + { name: 'Charlie', age: 30 }, + ]; + + expect>(Collection.groupBy(items, (item) => item.age)).toStrictEqual( + new Collection([ + [ + 20, + [ + { name: 'Alice', age: 20 }, + { name: 'Bob', age: 20 }, + ], + ], + [30, [{ name: 'Charlie', age: 30 }]], + ]), + ); + }); +}); + describe('toReversed() tests', () => { test('reverses a collection', () => { const coll = createTestCollection(); @@ -1152,5 +1175,8 @@ describe('subclassing tests', () => { test('Collection.combineEntries()', () => { expect(DerivedCollection.combineEntries([], Object)).toBeInstanceOf(DerivedCollection); }); + test('Collection.groupBy()', () => { + expect(DerivedCollection.groupBy([], Object)).toBeInstanceOf(DerivedCollection); + }); }); }); diff --git a/packages/collection/src/collection.ts b/packages/collection/src/collection.ts index 944df07a6..9d0a7c7f4 100644 --- a/packages/collection/src/collection.ts +++ b/packages/collection/src/collection.ts @@ -1088,6 +1088,17 @@ export class Collection extends Map { return coll; } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/groupBy | Map.groupBy()} + * but returns a Collection instead of a Map. + */ + public static override groupBy( + items: Iterable, + keySelector: (item: Item, index: number) => Key, + ): Collection { + return new this[Symbol.species](Map.groupBy(items, keySelector)); + } + /** * @internal */