shub
shub

Reputation: 1052

Extracting multiple object values

I have an object like this:

object["key1"] = "text1"
object["key2"] = "text2"
object["key3"] = "text1"
object["key4"] = "text3"

How can I give out (e.g. alert) the elements with the same values (text1, text2 and so on)?

In the above example it should be object["key1"] and object["key2"].

Thanks

Upvotes: 0

Views: 233

Answers (3)

Jacob
Jacob

Reputation: 78840

You could "invert" your object (properties become values, values become properties):

var byValue = {};

for (var prop in object) {
    if (!(object[prop] in byValue)) {
        byValue[object[prop]] = [];
    }
    byValue[object[prop]].push(prop);
}

This should yield this structure:

{
    'text1': ['key1', 'key3'],
    'text2': ['key2'],
    'text3': ['key4']
}

Then, you can detect those values that had duplicate keys:

for (var value in byValue) {
    if (byValue[value].length > 1) {
        alert(byValue[value].join(', '));
    }
}

Upvotes: 4

yunzen
yunzen

Reputation: 33439

I updated my script

http://jsfiddle.net/HerrSerker/LAnRt/

This does not check for identity in complex values, just for equality (see foo example)

Upvotes: 0

Bk Baba
Bk Baba

Reputation: 109

I have sorted the array and then considered that you would want to alert,or do any functionality, only once for every repeated element. WARNING: Sorting can get heavy with the size of the array http://jsfiddle.net/SPQJ7/ The above fiddle is already setup and working with multiple reapeated elements

Upvotes: 0

Related Questions