Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting lodash _.uniqBy() to native javascript

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.

like image 989
Gyanesh Gouraw Avatar asked Nov 25 '16 09:11

Gyanesh Gouraw


People also ask

What is Lodash uniqBy?

uniqBy method is similar to _. uniq except that it accepts iteratee which is invoked for each element in an array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array.

Do we really need Lodash?

But Sometimes You Do Need Lodash Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.

Is array equal Lodash?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.

Why do I need Lodash?

It's a utility library full of functions that make it easier to manipulate arrays, objects and strings. Lodash included so many critical functions that, for a long time, it was one of the first things developers would download when setting up a new project.


1 Answers

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));
like image 89
Ori Drori Avatar answered Sep 30 '22 11:09

Ori Drori