Converting lodash _.uniqBy() to native javascript

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

    Refactored @ori-drori's solution and removed

    1. undefined
    2. null
    3. extra numbers in mixed array
    4. return [] if first param is not Array

    const uniqBy = (arr, predicate) => {
      if (!Array.isArray(arr)) { return []; }
    
      const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate];
    
      const pickedObjects = arr
        .filter(item => item)
        .reduce((map, item) => {
            const key = cb(item);
    
            if (!key) { return map; }
    
            return map.has(key) ? map : map.set(key, item);
        }, new Map())
        .values();
     
      return [...pickedObjects];
    };
    
    const a = [ 
      12,
      undefined,
      { id: 1, name: 'bob' },
      null,
      { id: 1, name: 'bill' },
      null,
      undefined
    ];
    
    const b = [ 
      12,
      { id: 1, name: 'bob' },
      { id: 1, name: 'bill' },
    ];
    
    uniqBy(a, 'name');
    uniqBy(b, Math.floor);
    uniqBy([2.1, 1.2, 2.3], Math.floor);

提交回复
热议问题