Converting lodash _.uniqBy() to native javascript

后端 未结 4 754
傲寒
傲寒 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:10

    I'm running my code through Webpack via CreateReactApp, it must be using a polyfill for spread that uses slice. Here's what I did instead, a variation of @oridori's answer:

    const uniqBy = (arr: any[], predicate: (item: any) => string) => {
      const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate];
      const result = [];
      const map = new Map();
    
      arr.forEach((item) => {
        const key = (item === null || item === undefined) ? item : cb(item);
    
        if (!map.has(key)) {
          map.set(key, item);
          result.push(item);
        }
      });
    
      return result;
    };
    

提交回复
热议问题