Chris Jefferson
Chris Jefferson

Reputation: 7157

combining performing _.uniq with _.isEqual in lodash

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?

Upvotes: 6

Views: 3282

Answers (2)

santeko
santeko

Reputation: 510

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

Upvotes: 8

Adam Boduch
Adam Boduch

Reputation: 11211

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.

Upvotes: 2

Related Questions