Back to Articles

Distinct by - typescript snippet

2020-09-21

Source Code

1/**
2 * return a distinct array of items determined by a key function
3 * @param data
4 * @param key
5 * @param ignoreEmpty
6 */
7export function distinctBy<T, TY>(
8 data: T[],
9 key: (item: T) => TY,
10 ignoreEmpty?: boolean,
11) {
12 if (!data || data.length === 0) {
13 return data;
14 }
15
16 const hashSet = new Set<TY>();
17
18 return data.filter((x) => {
19 let keyVal: TY;
20 if (typeof key === 'string') {
21 keyVal = x[key];
22 } else {
23 keyVal = key(x);
24 }
25
26 if (!keyVal && ignoreEmpty) {
27 return false;
28 }
29
30 if (!hashSet.has(keyVal)) {
31 hashSet.add(keyVal);
32 return true;
33 }
34 return false;
35 });
36}
37

Execution Results

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