Back to Articles

Group by - typescript snippet

2020-09-21

Source Code

1/**
2 * group an array of items by the output of a key function
3 * @param arr
4 * @param getKey
5 */
6export function groupBy<T, TY>(
7 arr: T[],
8 getKey: (i: T) => TY,
9): { key: TY; items: T[] }[] {
10 const ret: { key: TY; items: T[] }[] = [];
11 arr.forEach((item) => {
12 const key = getKey(item);
13 const i = ret.find((r) => r.key === key);
14 if (!i) {
15 ret.push({ key, items: [item] });
16 } else {
17 i.items.push(item);
18 }
19 });
20
21 return ret;
22}
23

Execution Results

1groupBy([{ val: 1 }, { val: 1 }, { val: 2 }], function (r) { return r.val; }) === [{"key":1,"items":[{"val":1},{"val":1}]},{"key":2,"items":[{"val":2}]}]