Converting lodash _.uniqBy() to native javascript

后端 未结 4 674
傲寒
傲寒 2021-01-02 14:03

Here in this snippet i am stuck as in _.uniqBy(array,iteratee),this

  • iteratee can be a function or a string at the same time
4条回答
  •  被撕碎了的回忆
    2021-01-02 14:20

    An ES6 uniqBy using Map with a complexity of O(n):

    const uniqBy = (arr, predicate) => {
      const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate];
      
      return [...arr.reduce((map, item) => {
        const key = (item === null || item === undefined) ? 
          item : cb(item);
        
        map.has(key) || map.set(key, item);
        
        return map;
      }, new Map()).values()];
    };
    
    const sourceArray = [ 
      { id: 1, name: 'bob' },
      { id: 1, name: 'bill' },
      null,
      { id: 1, name: 'bill' } ,
      { id: 2,name: 'silly'},
      { id: 2,name: 'billy'},
      null,
      undefined
    ];
    
    console.log('id string: ', uniqBy(sourceArray, 'id'));
    
    console.log('name func: ', uniqBy(sourceArray, (o) => o.name));

提交回复
热议问题