Lodash remove duplicates from array
You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.
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
_.unique
no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique
was splitted into _.uniq
, _.sortedUniq
, _.sortedUniqBy
, and _.uniqBy
.
You could use _.uniqBy
like this:
_.uniqBy(data, function (e) {
return e.id;
});
...or like this:
_.uniqBy(data, 'id');
Documentation: https://lodash.com/docs#uniqBy
For older versions of Lodash (< 4.0.0 ):
Assuming that the data should be uniqued by each object's id
property and your data is stored in data
variable, you can use the _.unique()
function like this:
_.unique(data, function (e) {
return e.id;
});
Or simply like this:
_.uniq(data, 'id');