How can I check if the array of objects have duplicate property values?

JavascriptArraysUnique

Javascript Problem Overview


I need some help with iterating through array, I keep getting stuck or reinventing the wheel.

values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName1' },
    { name: 'someName1' }
]

How could I check if there are two (or more) same name value in array? I do not need a counter, just setting some variable if array values are not unique. Have in mind that array length is dynamic, also array values.

Javascript Solutions


Solution 1 - Javascript

Use array.prototype.map and array.prototype.some:

var values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName4' },
    { name: 'someName2' }
];

var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){ 
    return valueArr.indexOf(item) != idx 
});
console.log(isDuplicate);

Solution 2 - Javascript

ECMA Script 6 Version

If you are in an environment which supports ECMA Script 6's Set, then you can use Array.prototype.some and a Set object, like this

let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
    return seen.size === seen.add(currentObject.name).size;
});

Here, we insert each and every object's name into the Set and we check if the size before and after adding are the same. This works because Set.size returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.


ECMA Script 5 Version

If you don't have Set support, then you can use a normal JavaScript object itself, like this

var seen = {};
var hasDuplicates = values.some(function(currentObject) {

    if (seen.hasOwnProperty(currentObject.name)) {
        // Current name is already seen
        return true;
    }

    // Current name is being seen for the first time
    return (seen[currentObject.name] = false);
});

The same can be written succinctly, like this

var seen = {};
var hasDuplicates = values.some(function (currentObject) {
    return seen.hasOwnProperty(currentObject.name)
        || (seen[currentObject.name] = false);
});

Note: In both the cases, we use Array.prototype.some because it will short-circuit. The moment it gets a truthy value from the function, it will return true immediately, it will not process rest of the elements.

Solution 3 - Javascript

In TS and ES6 you can create a new Set with the property to be unique and compare it's size to the original array.

const values = [
  { name: 'someName1' },
  { name: 'someName2' },
  { name: 'someName3' },
  { name: 'someName1' }
]

const uniqueValues = new Set(values.map(v => v.name));

if (uniqueValues.size < values.length) {
  console.log('duplicates found')
}

Solution 4 - Javascript

> To know if simple array has duplicates we can compare first and last indexes of the same value:

The function:

var hasDupsSimple = function(array) {

    return array.some(function(value) {                            // .some will break as soon as duplicate found (no need to itterate over all array)
       return array.indexOf(value) !== array.lastIndexOf(value);   // comparing first and last indexes of the same value
    })
}

Tests:

hasDupsSimple([1,2,3,4,2,7])
// => true

hasDupsSimple([1,2,3,4,8,7])
// => false

hasDupsSimple([1,"hello",3,"bye","hello",7])
// => true

> For an array of objects we need to convert the objects values to a simple array first:

Converting array of objects to the simple array with map:

var hasDupsObjects = function(array) {

  return array.map(function(value) {
    return value.suit + value.rank

  }).some(function(value, index, array) { 
       return array.indexOf(value) !== array.lastIndexOf(value);  
     })
}

Tests:

var cardHand = [  { "suit":"spades", "rank":"ten" },  { "suit":"diamonds", "rank":"ace" },  { "suit":"hearts", "rank":"ten" },  { "suit":"clubs", "rank":"two" },  { "suit":"spades", "rank":"three" },]

hasDupsObjects(cardHand);
// => false

var cardHand2 = [  { "suit":"spades", "rank":"ten" },  { "suit":"diamonds", "rank":"ace" },  { "suit":"hearts", "rank":"ten" },  { "suit":"clubs", "rank":"two" },  { "suit":"spades", "rank":"ten" },]

hasDupsObjects(cardHand2);
// => true

Solution 5 - Javascript

if you are looking for a boolean, the quickest way would be

var values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName1' },
    { name: 'someName1' }
]

// solution
var hasDuplicate = false;
values.map(v => v.name).sort().sort((a, b) => {
  if (a === b) hasDuplicate = true
})
console.log('hasDuplicate', hasDuplicate)

Solution 6 - Javascript

Try an simple loop:

var repeat = [], tmp, i = 0;

while(i < values.length){
  repeat.indexOf(tmp = values[i++].name) > -1 ? values.pop(i--) : repeat.push(tmp)
}

Demo

Solution 7 - Javascript

You just need one line of code.

var values = [
        { name: 'someName1' },
        { name: 'someName2' },
        { name: 'someName4' },
        { name: 'someName2' }
     ];
        let hasDuplicates = values.map(v => v.name).length > new Set(values.map(v => v.name)).size ? true : false;

Solution 8 - Javascript

With Underscore.js A few ways with Underscore can be done. Here is one of them. Checking if the array is already unique.

function isNameUnique(values){
    return _.uniq(values, function(v){ return v.name }).length == values.length
}

With vanilla JavaScript By checking if there is no recurring names in the array.

function isNameUnique(values){
    var names = values.map(function(v){ return v.name });
    return !names.some(function(v){ 
        return names.filter(function(w){ return w==v }).length>1 
    });
}

Solution 9 - Javascript

//checking duplicate elements in an array
var arr=[1,3,4,6,8,9,1,3,4,7];
var hp=new Map();
console.log(arr.sort());
var freq=0;
for(var i=1;i<arr.length;i++){
// console.log(arr[i-1]+" "+arr[i]);
if(arr[i]==arr[i-1]){
freq++;

}
else{
hp.set(arr[i-1],freq+1);
freq=0;
}
}
console.log(hp);

Solution 10 - Javascript

const values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName4' },
    { name: 'someName4' }
];

const foundDuplicateName = values.find((nnn, index) =>{
   return values.find((x, ind)=> x.name === nnn.name && index !== ind )
    })
    
    console.log(foundDuplicateName)

Found the first one duplicate name

const values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName4' },
    { name: 'someName4' }
];

const foundDuplicateName = values.find((nnn, index) =>{
   return values.find((x, ind)=> x.name === nnn.name && index !== ind )
    })

Solution 11 - Javascript

You can use map to return just the name, and then use this forEach trick to check if it exists at least twice:

var areAnyDuplicates = false;

values.map(function(obj) {
    return obj.name;
}).forEach(function (element, index, arr) {
    if (arr.indexOf(element) !== index) {
        areAnyDuplicates = true;
    }
});

Fiddle

Solution 12 - Javascript

Adding updated es6 function to check for unique and duplicate values in array. This function is modular and can be reused throughout the code base. Thanks to all the post above.



/* checks for unique keynames in array */
const checkForUnique = (arrToCheck, keyName) => {
    /* make set to remove duplicates and compare to  */
  const uniqueValues = [...new Set(arrToCheck.map(v => v[keyName]))];
  if(arrToCheck.length !== uniqueValues.length){
    console.log('NOT UNIQUE')
    return false
  }
  return true
}


let arr = [{name:'joshua'},{name:'tony'},{name:'joshua'}]

/* call function with arr and key to check for  */
let isUnique = checkForUnique(arr,'name')




Solution 13 - Javascript

Try this function it extends your original question by going one step to delete duplicates. You get a return array with duplicates removed.

const test = [
    { name: 'someName1' },
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName3' }
]

function removeDup(arrayOfObjects) {
  if (new Set(arrayOfObjects.map((v) => v.name)).size < arrayOfObjects.length) {
          const _set = new Set();
          const _data = arrayOfObjects;
          for (const i in _data) {
            _set.add(JSON.stringify(_data[i]));
          }
          return Array.from(_set).map((i) =>
            JSON.parse(i)
          );
        }
}

const res = removeDup(test)
console.log(res)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbe-codifiedView Question on Stackoverflow
Solution 1 - JavascriptAmir PopovichView Answer on Stackoverflow
Solution 2 - JavascriptthefourtheyeView Answer on Stackoverflow
Solution 3 - Javascriptlukas_oView Answer on Stackoverflow
Solution 4 - JavascriptSystems RebooterView Answer on Stackoverflow
Solution 5 - Javascriptuser2167582View Answer on Stackoverflow
Solution 6 - JavascriptWalter Chapilliquen - wZVanGView Answer on Stackoverflow
Solution 7 - JavascriptSaif ShaikhView Answer on Stackoverflow
Solution 8 - JavascriptTaoPRView Answer on Stackoverflow
Solution 9 - JavascriptraviView Answer on Stackoverflow
Solution 10 - JavascriptRichylandView Answer on Stackoverflow
Solution 11 - JavascriptOmri AharonView Answer on Stackoverflow
Solution 12 - JavascriptJoshView Answer on Stackoverflow
Solution 13 - JavascriptnanacnoteView Answer on Stackoverflow