Categories
JavaScript Answers

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

Spread the love

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.

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 *