admin管理员组

文章数量:1431705

Given the following object:

answers = {'a': 3,'b': 2,'c': 3, 'd': 1};

How can I find whether or not there is a duplicate value? I need to write a condition that will say if two of these have the same value, then console.log('duplicate values found').

Given the following object:

answers = {'a': 3,'b': 2,'c': 3, 'd': 1};

How can I find whether or not there is a duplicate value? I need to write a condition that will say if two of these have the same value, then console.log('duplicate values found').

Share Improve this question edited Mar 2, 2016 at 17:51 Pdnell asked Mar 2, 2016 at 17:48 PdnellPdnell 3214 silver badges16 bronze badges 3
  • 2 Objects can't have duplicate keys. – Mike Cluck Commented Mar 2, 2016 at 17:49
  • Yes, I am aware. I'm looking for a test that will return whether or not there are duplicate values in there. – Pdnell Commented Mar 2, 2016 at 17:51
  • Can the values themselves be objects etc.? – user663031 Commented Mar 3, 2016 at 10:30
Add a ment  | 

2 Answers 2

Reset to default 3

You have to write a nested loop to find that,

var keys = Object.keys(answers);
var dupe = false;

for(var i=0;i<keys.length;i++){
 for(var j=i+1;j<keys.length;j++){
   if(answers[keys[i]] === answers[keys[j]]){
     dupe = true;
     break;
   }
 }
 if(dupe){ console.log("dupe value is there.."); break; }
}

DEMO

I guess you mean duplicate values and not duplicate key/value pairs. This is how I'd do it:

function findDuplicateValues(input) {
    var values = {},
        key;

    for (key in input) {
        if (input.hasOwnProperty(key)) {
            values[input[key]] = values.hasOwnProperty(input[key]) ? values[input[key]] + 1 : 1;
        }
    }

    for (key in values) {
        if (values.hasOwnProperty(key) && values[key] > 1) {
            console.log('duplicate values found');
            break;
        }
    }
}

For large objects it will be quicker than the previous answer, because there are no nested loops (this will execute in linear O(n) time rather than quadratic O(n2) time).

本文标签: Find duplicate value in JavaScript objectStack Overflow