The documentation for uniq()
function mentions that it runs much faster if the list is sorted. Also using the chained calls can improve readability. So you can do:
_.chain(c1).union(c2).sortBy("a").uniq(true, function(item){ return item.a; }).value();
Or if you prefer the unchained version (which is 11 characters shorter but less readable):
_.uniq(_.sortBy(_.union(c1,c2),"a"),true, function(item){ return item.a; });
The documentation and examples for uniq()
don't make it clear how the callback function works. The algorithm for uniq()
function calls this function on every element from both lists. If the result of this function is the same, it removes that element (assuming it is duplicated).
union()
in fact prevents duplicates when called on an array. We can use this fact too:
_.map(_.union(_.pluck(c1,"a"),_.pluck(c2,"a")),function (item) {return {a:item};});
The above like first converts the list of objects to simple arrays (pluck()
) then combines them using union()
and eventually uses map()
to make a list of objects.
Reference: uniq()