objectGroupBy.ts
1 /** 2 * https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.groupby 3 */ 4 export function objectGroupBy<T, K extends PropertyKey>( 5 items: Iterable<T>, 6 keySelector: (item: T, index: number) => K, 7 ): Partial<Record<K, T[]>> { 8 const result = Object.create(null) as Partial<Record<K, T[]>> 9 let index = 0 10 for (const item of items) { 11 const key = keySelector(item, index++) 12 if (result[key] === undefined) { 13 result[key] = [] 14 } 15 result[key].push(item) 16 } 17 return result 18 }