To check if the JavaScript array of objects have duplicate property values, we can compare its size to its set equivalent.
For instance, we write
const values = [
{ name: "name1" },
{ name: "name2" },
{ name: "name3" },
{ name: "name1" },
];
const uniqueValues = new Set(values.map((v) => v.name));
if (uniqueValues.size < values.length) {
console.log("duplicates found");
}
to create a set with the Set
constructor with an array of name
property values from each object.
Then we compare the size
of the set to the length
of the array to check if there’re any duplicates.
If the size of the set is smaller than the array’s length, then there are duplicates.