EN
JavaScript - check if array of objects has duplicate property values
3
points
In this article, we would like to show you how to check if an array of objects has duplicate property values in JavaScript.
1. Using Set
class (ES6)
In this example, we add unique property values to Set
and compare the size changes to detect duplicate property values.
// ONLINE-RUNNER:browser;
const array = [
{property: 'value1'},
{property: 'value1'},
{property: 'value2'}
];
const set = new Set();
if (array.some((object) => set.size === (set.add(object.property), set.size))) {
console.log('Array has duplicated property values!');
}
2. Using map()
and some()
methods (ES5)
In this example, we check if an array of objects has duplicate property values in the following steps:
- create property
values
array, - check property
values
array duplicates usingsome()
method.
// ONLINE-RUNNER:browser;
const array = [
{property: 'value1'},
{property: 'value1'},
{property: 'value2'}
];
const values = array.map((object) => object.property);
if (values.some((object, index) => values.indexOf(object) !== index)) {
console.log('Array has duplicated property values!');
}
Note:
This solution may have a bad performance for large arrays.