-
Notifications
You must be signed in to change notification settings - Fork 7
/
uniq-by.ts
49 lines (38 loc) · 1.07 KB
/
uniq-by.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// * try ramda https://ramdajs.com/docs/#uniqBy
// * ------------------------------------------------ uniqBy (key) simple
const uniqBy = <T, K extends any>(arr: T[], byKey: (ele: T) => K = (e) => e as any): T[] => {
const map = new Set<K>();
const result = arr.filter((e) => {
const key = byKey(e);
if (map.has(key)) {
return false;
} else {
map.add(key);
return true;
}
});
return result;
};
// * ------------------------------------------------ usage
{
const data = [
{ key: 1, val: 'Lorem' },
{ key: 2, val: 'ipsum' },
{ key: 3, val: 'dolor' },
{ key: 1, val: 'sit' },
{ key: 1, val: 'amet' },
{ key: 2, val: 'consectetur' },
{ key: 4, val: 'adipisicing' },
];
const expected = [
{ key: 1, val: 'Lorem' },
{ key: 2, val: 'ipsum' },
{ key: 3, val: 'dolor' },
{ key: 4, val: 'adipisicing' },
];
const result = uniqBy(data, (e) => e.key);
console.log('--------');
console.assert(JSON.stringify(result) === JSON.stringify(expected));
console.log(result);
console.log('--------');
}