Categories
JavaScript Answers

How to check if the array of objects have duplicate property values with JavaScript?

Spread the love

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 valueslength, 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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *