Back

Group by - typescript snippet

2021-01-01

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 extends string | number>(
7 arr: T[],
8 getKey: (i: T) => TY,
9): { [key in TY]: T[] } {
10 const ret: { [key in TY]: T[] } = {} as { [key in TY]: T[] };
11 arr.forEach((item) => {
12 const key = getKey(item);
13 if (!ret[key]) {
14 ret[key] = [];
15 }
16
17 ret[key].push(item);
18 });
19
20 return ret;
21}
22
23/**
24 * group an array of items by the output of a key function
25 * @param arr
26 * @param getKey
27 */
28export function groupByList<T, TY>(
29 arr: T[],
30 getKey: (i: T) => TY,
31): { key: TY; items: T[] }[] {
32 const ret: { key: TY; items: T[] }[] = [];
33 arr.forEach((item) => {
34 const key = getKey(item);
35 const i = ret.find((r) => r.key === key);
36 if (!i) {
37 ret.push({ key, items: [item] });
38 } else {
39 i.items.push(item);
40 }
41 });
42
43 return ret;
44}
45
46export function groupByTwice<T>(
47 arr: T[],
48 getKey: (i: T) => string | number,
49 getSubKey: (i: T) => string | number,
50): { [key in string | number]: { [a in string | number]: T } } {
51 const ret: { [key in string | number]: { [a in string | number]: T } } = {};
52 arr.forEach((item) => {
53 const key = getKey(item);
54 const subkey = getSubKey(item);
55 if (!ret[key]) {
56 ret[key] = {};
57 }
58
59 ret[key][subkey] = item;
60 });
61
62 return ret;
63}
64

Execution Results

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