0

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

3
  • Um...loop through the array and test each value? Commented Sep 30, 2011 at 7:06
  • That's not an array, that's an object. Arrays in JavaScript only have numerical keys. Commented Sep 30, 2011 at 8:17
  • 2
    I assume you mean object['key1'] and object['key3']? Commented Sep 30, 2011 at 18:41

3 Answers 3

4

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(', '));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

I updated my script

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

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

Comments

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.