本文介绍了将lodash _.uniqBy()转换为本地javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码段中,我像在_.uniqBy(array,iteratee)中一样被卡住

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

  • iteratee可以同时是函数或字符串
  • 在哪里放置条件以检查属性的唯一性,因为itratee函数可以是任何东西
  • iteratee can be a function or a string at the same time
  • Where to put the condition to check uniqness on the property because itratee function can be anything
var sourceArray = [ { id: 1, name: 'bob' },
  { id: 1, name: 'bill' },
  { id: 1, name: 'bill' } ,
  {id: 2,name: 'silly'},
  {id: 2,name: 'billy'}]

function uniqBy (inputArray, callback) {
  return inputArray.filter(callback)
}
var inputFunc = function (item) {
  return item.name
}

// var destArray = _.uniqBy(sourceArray,'name')

var destArray = uniqBy(sourceArray, inputFunc)
console.log('destArray', destArray)

对此,任何线索都将受到赞赏.

Any leads on this will be most appreciated.

推荐答案

使用 Map ,复杂度为O(n):

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));

这篇关于将lodash _.uniqBy()转换为本地javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 01:38