Sometimes, we want to check if the array of objects have duplicate property values with JavaScript.
In this article, we’ll look at how to check if the array of objects have duplicate property values with JavaScript.
How to check if the array of objects have duplicate property values with JavaScript?
To check if the array of objects have duplicate property values with JavaScript, we create a set from the property of each array entry that we want to check for duplicates for.
For instance, we write
const values = [
{ name: "someName1" },
{ name: "someName2" },
{ name: "someName3" },
{ name: "someName1" },
];
const uniqueValues = new Set(values.map((v) => v.name));
if (uniqueValues.size < values.length) {
console.log("duplicates found");
}
to get the name
property values of each values
array entry with
values.map((v) => v.name)
Then we convert the array to a set with the Set
constructor.
If the set’s size
is less than values
‘ length
, then we know there’re duplicates values in values
.
Conclusion
To check if the array of objects have duplicate property values with JavaScript, we create a set from the property of each array entry that we want to check for duplicates for.