Languages
[Edit]
EN

JavaScript - check if array of objects has duplicate property values

3 points
Created by:
Inayah-Alexander
767

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:

  1. create property values array,
  2. check property values array duplicates using some() 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.

 

References

  1. Array.prototype.map() - JavaScript | MDN
  2. Array.prototype.some() - JavaScript | MDN
  3. Array.prototype.indexOf() - JavaScript | MDN

Alternative titles

  1. JavaScript - check if array of objects contains duplicate property values
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join