Converting lodash _.uniqBy() to native javascript

lodash uniqby
lodash chain
lodash compare objects
lodash debounce example
lodash vs underscore
lodash remove duplicates from two arrays
uniqby is not a function
lodash get unique values from array

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)

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

Documentation, Converts all elements in array into a string separated by separator . is like _. uniqBy except that it's designed and optimized for sorted arrays. var flipped = _. flip(function() { Note: This method can't reliably detect native functions in the presence of the core-js package because core-js circumvents this kind of detection. _.uniqBy(array, [iteratee=_.identity]) source npm package This method is like _.uniq except that it accepts iteratee which is invoked for each element in array to generate the criterion by which uniqueness is computed.

I'm running my code through Webpack via CreateReactApp, it must be using a polyfill for spread that uses slice. Here's what I did instead, a variation of @oridori's answer:

const uniqBy = (arr: any[], predicate: (item: any) => string) => {
  const cb = typeof predicate === 'function' ? predicate : (o) => o[predicate];
  const result = [];
  const map = new Map();

  arr.forEach((item) => {
    const key = (item === null || item === undefined) ? item : cb(item);

    if (!map.has(key)) {
      map.set(key, item);
      result.push(item);
    }
  });

  return result;
};

Lodash remove duplicates from array Code Example, uniqBy(users,'id'); //removed if had duplicate id. 8. var uniqueUsers = _. Javascript queries related to “Lodash remove duplicates from array”. Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodash’s modular methods are great for: Iterating arrays, objects, & strings; Manipulating & testing values; Creating composite functions. Module Formats. Lodash is available in a variety of builds & module formats. lodash & per

You could use a sort ordered by name and a filter based on the neighborhood comparison like this :

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)

converting lodash's pickby in to javascript, (Array): Returns the converted array. Converting lodash _.uniqBy () to native javascript iteratee can be a function or a string at the same time Where to put the � A modern JavaScript utility library delivering modularity, performance, & extras. - lodash/lodash

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

10 Lodash Features You Can Replace with ES6, Dan Prince demonstrates ten ways you can use native ES6 features (such as arrow functions & collection methods) to replace Lodash in your projects. These collection methods make transforming data a breeze and with near the evolved version of JavaScript is allowing us to solve some problems in� ⬆back to top. Collection* Important: Note that most native equivalents are array methods, and will not work with objects. If this functionality is needed and no object method is provided, then Lodash/Underscore is the better option.

lodash.uniqBy JavaScript and Node.js code examples, unionWith; _.uniq; _.uniqBy; _.uniqWith; _.unzip; _.unzipWith; _.without; _.xor; _. Converts all elements in array into a string separated by separator . Note: This method can't reliably detect native functions in the presence of the core-js package because core-js circumvents this kind of detection. _.prototype.commit (). Tag: javascript,lodash [Update]: I've removed most of the layout and lodash (failed code) from before because the JSON data format has changed. I'm trying to group a data set in preparation for aggregating totals.

Generated docs for Lodash/fp. Help make them better at https , Underscore is a JavaScript library that provides a whole mess of useful functional If you need to cancel a scheduled debounce, you can call .cancel() on the debounced function. Convert an object into a list of [key, value] pairs. Note: this is not the same as the native isNaN function, which will also return true for many� Lodash's map method works exactly like Javascript native array method except that it has a sweet upgrade. It's able to navigate deeply-nested property by just providing a string instead of a callback function. Take note: There is a much more specific method for this use-case: _.pluck. Apparently _.pluck will be removed in

Underscore.js, Underscore.js | _.uniq() with Examples. 14-12-2018. The Underscore.js is a JavaScript library that provides a lot of useful functions like the map, filter, invoke etc� Lodash makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc. Lodash’s modular methods are great for:

Comments
  • Check lodash.uniqBy() code
  • Yeah, have a look and see if the source code helps: github.com/lodash/lodash/blob/4.17.2/lodash.js#L8419
  • When there is a Object/item with null or undefined it breaks. Lodash handles this differently. E.g: _.uniqBy([{ 'x': 1 }, null, { 'x': 1 }, { 'y': 1 }], 'x'). Results into: [Object{x: 1}, null]
  • @M.Suurland - good catch. Updated answer to handle null and undefined values in the same way.
  • I like this implementation, but I keep getting ".slice() is not a function". Any ideas?
  • My solution contain 0 uses of .slice() so I can't really help you with the :)
  • I'm running my code through Webpack via CreateReactApp, it must be using a polyfill for spread that uses slice. I posted a variation of your solution: stackoverflow.com/a/59218578/2691271 (inline code doesn't work so well :)