showing results for - "lodash uniqby alterantive in js"
Lorenzo
09 Aug 2019
1const uniqBy = (arr, predicate) => {
2  const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate];
3  
4  return [...arr.reduce((map, item) => {
5    const key = (item === null || item === undefined) ? 
6      item : cb(item);
7    
8    map.has(key) || map.set(key, item);
9    
10    return map;
11  }, new Map()).values()];
12};
13
14const sourceArray = [ 
15  { id: 1, name: 'bob' },
16  { id: 1, name: 'bill' },
17  null,
18  { id: 1, name: 'bill' } ,
19  { id: 2,name: 'silly'},
20  { id: 2,name: 'billy'},
21  null,
22  undefined
23];
24
25console.log('id string: ', uniqBy(sourceArray, 'id'));
26
27console.log('name func: ', uniqBy(sourceArray, (o) => o.name));
similar questions
queries leading to this page
lodash uniqby alterantive in js