1

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').

3
  • 2
    Objects can't have duplicate keys. 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. Commented Mar 2, 2016 at 17:51
  • Can the values themselves be objects etc.? Commented Mar 3, 2016 at 10:30

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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).

1 Comment

This won't work if the values are objects. Anyway, why don't you just issue the message and return the minute you find the second one?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.