How to Check if the Array of Objects Have Duplicate Property Values with JavaScript? | by John Au-Yeung | Mar, 2024
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.
To check if the array of objects have duplicate property values with JavaScript, we can use the JavaScript array’s map
and some
method to map the array to the property values we want to check.
Then we can use the indexOf
method in the some
callback to check if an element in the mapped array is the first instance or not.
For instance, we can write:
const values = [{
name: 'someName1'
},
{
name: 'someName2'
},
{
name: 'someName4'
},
{
name: 'someName2'
}
];const valueArr = values.map((item) => {
return item.name
});
const isDuplicate = valueArr.some((item, idx) => {
return valueArr.indexOf(item) !== idx
});
console.log(isDuplicate);
We have the values
array that we want to check if there’re duplicate values of the name
property.
Then we call map
to return an array with the name
property values and assign it to valueArr
.
Next, we call valueArr.some
with a callback that checks if idx
is different from the index returned by indexOf
.
Since indexOf
returns the index of the first instance of a value, that means if idx
is different from what’s returned with indexOf
, we know it’s a duplicate value.
Therefore, since we have a duplicate value of name
in 2 entries, isDuplicate
is true
and that’s logged in the console log.
To check if the array of objects have duplicate property values with JavaScript, we can use the JavaScript array’s map
and some
method to map the array to the property values we want to check.
Then we can use the indexOf
method in the some
callback to check if an element in the mapped array is the first instance or not.
Source link