Nomad
Nomad

Reputation: 1102

javascript: get keys containing duplicate data in an associative array

I have a javascript associative array. It will be populated dynamically.

I want to find the keys which will contain the duplicate data/values.

For simplicity, it will look like this.

var p =   { };
 p =
    {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3",
        "p4": "value2",
        "p5": "value3",
        "p6": "value5"
    };

How can i do this.

Here's the js fiddle.

jsfiddle

Is there other way than using hasOwnProperty?

Any ideas to make this work?

Upvotes: 0

Views: 2692

Answers (3)

phuzi
phuzi

Reputation: 13079

var p =
    {
        "p1": "value1",
        "p2": "value2",
        "p3": "value3",
        "p4": "value2",
        "p5": "value3",
        "p6": "value5"
    };

var q = {};
var keys = Object.keys(p);
for (var i = 0; i < keys.length; i++) {
    var currentKey = keys[i];
    var newKey = p[currentKey];
    if (q[newKey] === undefined){
        q[newKey] = [];
    }
    q[newKey].push(currentKey);
}

This will get you an object looking something like:

{
  "value1": ["p1"],
  "value2": ["p2","p4"],
  "value3": ["p3","p5"],
  "value5": ["p6"]
}

Upvotes: 3

nrabinowitz
nrabinowitz

Reputation: 55678

A slightly tighter version of @RocketHazmat's solution:

var values = {},
    dupes = [],
    key,
    val;
for (key in p) {
    if (p.hasOwnProperty(key)) {
        val = p[key];
        if (values[val]) dupes.push(key);
        else values[val] = true;
    }
}

This just gives you a list of keys with dupes. (Note - the first instance of a dupe value isn't considered a dupe here.)

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227310

Simplest way I can think of is to loop through your current object, and mark each value you see. When you see a value again, mark that key.

var tmp = {};
for(var i in p){
    var val = p[i];

    // Have we seen this value before?
    if(!tmp.hasOwnProperty(val)){
        // Mark the value as seen for the first time
        tmp[val] = []; // 0 duplicates
    }
    else{
        // We've seen it before, save the duplicate key
        tmp[val].push(i);
    }
}

// Print out values and their duplicate keys
for(var i in tmp){
    var keys = tmp[i];

    // Are there any duplicates?
    if(keys.length){
        alert(i + ' has multiple keys: '+keys.join(', '));
    }
}

DEMO: http://jsfiddle.net/bjRDK/

Upvotes: 2

Related Questions