When working with an array of objects, it's often necessary to remove duplicates. The ES6 filter method provides an elegant solution for this task.
obj.arr = obj.arr.filter((value, index, self) =>
index === self.findIndex((t) => (
t.place === value.place && t.name === value.name
))
)
This code compares each element in the array with all subsequent elements. If a duplicate is found, it is filtered out.
For a more generic approach:
const uniqueArray = obj.arr.filter((value, index) => {
const _value = JSON.stringify(value);
return index === obj.arr.findIndex(obj => {
return JSON.stringify(obj) === _value;
});
});
This strategy serializes each object to a string and compares the strings to identify duplicates.
Using the property strategy:
const getUniqueItemsByProperties = (items, propNames) =>
items.filter((item, index, array) =>
index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
);
This approach provides flexibility in specifying the properties on which uniqueness is determined.
To allow for both array and single property names:
const getUniqueItemsByProperties = (items, propNames) => {
const propNamesArray = Array.from(propNames);
return items.filter((item, index, array) =>
index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))
);
};
The key idea here is to use the filter method to identify duplicates. The uniqueness criteria is determined by the comparison logic, which can be customized based on the object properties or a serialization strategy.
The above is the detailed content of How to Efficiently Remove Duplicate Objects from an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!