I have an array of objects with duplicates and I\'m trying to get a unique listing, where uniqueness is defined by a subset of the properties of the object. For example,
Use Lodash's uniqWith method:
_.uniqWith(array, [comparator])This method is like
_.uniqexcept that it acceptscomparatorwhich is invoked to compare elements ofarray. The order of result values is determined by the order they occur in the array.The comparator is invoked with two arguments: (arrVal, othVal).
When the comparator returns true, the items are considered duplicates and only the first occurrence will be included in the new array.
Example:
I have a list of locations with latitude and longitude -- some of which are identical -- and I want to see the list of unique locations:
const locations = [
{
name: "Office 1",
latitude: -30,
longitude: -30
},
{
name: "Office 2",
latitude: -30,
longitude: 10
},
{
name: "Office 3",
latitude: -30,
longitude: 10
}
];
const uniqueLocations = _.uniqWith(
locations,
(locationA, locationB) =>
locationA.latitude === locationB.latitude &&
locationA.longitude === locationB.longitude
);
// Result has Office 1 and Office 2