2016-11-25 63 views
2

在这里,在这个片段中我被困在_.uniqBy(array,iteratee),这转换lodash _.uniqBy()到本地JavaScript

  • iteratee可以是一个函数或在同一时间的字符串
  • 哪里摆放条件检查uniqness的财产,因为itratee功能可以是任何东西

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)

对此的任何线索将不胜感激。

+0

[检查lodash.uniqBy()代码](https://github.com/lodash/lodash/blob/master/lodash.js#L4253) – GillesC

+0

是的,看看源代码是否有帮助:https ://github.com/lodash/lodash/blob/4.17.2/lodash.js#L8419 – Fernando

回答

0

你可以使用按名称排序排序,并根据附近比较像这样的过滤器:使用Map用O(n)的复杂性

var sourceArray = [ { id: 1, name: 'bob' }, 
 
    { id: 1, name: 'bill' }, 
 
    { id: 1, name: 'bill' } , 
 
    {id: 2,name: 'silly'}, 
 
    {id: 2,name: 'billy'}] 
 

 
var uniqBy = (inputArray, callback) => inputArray.sort((a,b) => callback(a) > callback(b)) 
 
.filter((x,i,arr) => i === arr.length -1 ? true : callback(x) !== callback(arr[i+1])); 
 
var inputFunc = item => item.name; 
 

 

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

2

的ES6 uniqBy

const uniqBy = (arr, predicate) => { 
 
    const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate]; 
 
    
 
    return [...arr.reduce((map, item) => { 
 
    const key = cb(item); 
 
    
 
    map.has(key) || map.set(key, item); 
 
    
 
    return map; 
 
    }, new Map()).values()]; 
 
}; 
 

 
const sourceArray = [ 
 
    { id: 1, name: 'bob' }, 
 
    { id: 1, name: 'bill' }, 
 
    { id: 1, name: 'bill' } , 
 
    { id: 2,name: 'silly'}, 
 
    { id: 2,name: 'billy'} 
 
]; 
 

 
console.log('id string: ', uniqBy(sourceArray, 'id')); 
 

 
console.log('name func: ', uniqBy(sourceArray, (o) => o.name));