Lodash remove duplicates from array

Lodash remove duplicates from array

This is my data:
[
{
url: ‘www.example.com/hello’,
id: “22”
},
{
url: ‘www.example.com/hello’,
id: “22”
},
{
url: ‘www.example.com/hello-how-are-you’,
id: “23”
},
{
url: ‘www.example.com/i-like-cats’,
id: “24”
},
{
url: ‘www.example.com/i-like-pie’,
id: “25”
}
]

With Lodash, how could I remove objects with duplicate id keys?
Something with filter, map and unique, but not quite sure.
My real data set is much larger and has more keys, but the concept should be the same.

Solutions/Answers:

Solution 1:

_.uniq no longer work for the current version as lodash 4.0.0 has this breaking change. So use either

_.uniqBy(data, function (e) {
  return e.id;
});

or

_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy


For older versions of lodash( < 4.0.0 )

Assuming that the data should be unique by id and your data is stored in data variable, you can use uniq() function like this:

_.uniq(data, function (e) {
  return e.id;
});

Or simply

_.uniq(data, 'id');

Solution 2:

You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.

Related:  How can I access Google Sheet spreadsheets only with Javascript?

Example:

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

Solution 3:

Or simply Use union, for simple array.

Solution 4:

Simply use _.uniqBy(). It creates duplicate-free version of an array.

This is a new way and available from 4.0.0 version.

_.uniqBy(data, 'id');

or

_.uniqBy(data, obj => obj.id);

Solution 5:

You can also use unionBy for 4.0.0 and later, as follows:
let uniques = _.unionBy(data, ‘id’)