Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining performing _.uniq with _.isEqual in lodash

Tags:

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?

like image 449
Chris Jefferson Avatar asked Jun 02 '15 20:06

Chris Jefferson


2 Answers

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

like image 137
santeko Avatar answered Oct 18 '22 00:10

santeko


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.

like image 36
Adam Boduch Avatar answered Oct 18 '22 00:10

Adam Boduch