To check for duplicate values in an array of objects, you can use the reduce()
method to create an object where each key represents a unique value and the corresponding value is the number of times that value appears in the array. Here’s an example code snippet:
const data = [
{
"id": 1,
"docNo": "doc123",
},
{
"id": 2,
"docNo": "doc456",
},
{
"id": 3,
"docNo": "doc123",
}
];
const docNoCounts = data.reduce((counts, obj) => {
counts[obj.docNo] = (counts[obj.docNo] || 0) + 1;
return counts;
}, {});
console.log(docNoCounts); // Output: { "doc123": 2, "doc456": 1 }
In this example, the reduce()
method initializes an empty object as the initial value. Then, for each object in the array, it checks if the docNo
property already exists as a key in the object. If it does, it increments the count value by 1. If not, it adds the docNo
property as a new key in the object with an initial value of 1. Finally, the reduce()
method returns the object with the count values for each docNo
value.
You can then check if there are any duplicate values by iterating over the docNoCounts
object and checking if any of the values are greater than 1. For example:
for (const docNo in docNoCounts) {
if (docNoCounts[docNo] > 1) {
console.log(`Duplicate docNo value found: ${docNo}`);
}
}