Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  162] [ 7]  / answers: 1 / hits: 20845  / 8 Years ago, fri, november 25, 2016, 12:00:00

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

  • 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.


More From » arrays

 Answers
6

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




[#59924] Wednesday, November 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
briannar

Total Points: 354
Total Questions: 103
Total Answers: 101

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;