lodash provides a method _.uniq()
to find unique elements from an array, but the comparison function used is strict equality ===
, while I want to use _.isEqual()
, which satisfies:
_.isEqual([1, 2], [1, 2])
// true
Is there a way to perform _.uniq()
with _.isEqual()
, without writing my own method?
As of lodash v4 there's _.uniqWith(array, _.isEqual)
.
from the docs:
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// → [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
more info: https://lodash.com/docs#uniqWith
While you can't use isEqual() with uniq(), what you're asking for seems perfectly reasonable and deserves a solution. Here's the best (clean/performant) I could come up with:
_.reduce(coll, function(results, item) {
return _.any(results, function(result) {
return _.isEqual(result, item);
}) ? results : results.concat([ item ]);
}, []);
You can use reduce() to build an array of unique values. The any() function uses isEqual()
to check if the current item is already in the results. If not, it adds it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With