ChrisRich ChrisRich - 1 year ago 482
Javascript Question

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.

Answer Source

_.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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download