33
var associativeArray = [];

associativeArray['key1'] = 'value1';
associativeArray['key2'] = 'value2';
associativeArray['key3'] = 'value3';
associativeArray['key4'] = 'value4';
associativeArray['key5'] = 'value5';

var key = null;
for(key in associativeArray)
{
    console.log("associativeArray[" + key + "]: " +  associativeArray[key]);        
}

key = 'key3';

var obj = associativeArray[key];        

// gives index = -1 in both cases why?
var index = associativeArray.indexOf(obj); 
// var index = associativeArray.indexOf(key);  

console.log("obj: " + obj + ", index: " + index);   

The above program prints index: -1, why? Is there any better way to get index of an object in an associative array without using loops?

What if I want to delete 'key3' from this array? the splice function takes first parameter as index which must be an integer.

3

3 Answers 3

42

indexOf only works with pure Javascript arrays, i.e. those with integer indexes. Your "array" is actually an object and should be declared as such

var associativeArray = {}

There's no built-in indexOf for objects, but it's easy to write.

var associativeArray = {}

associativeArray['key1'] = 'value1';
associativeArray['key2'] = 'value2';
associativeArray['key3'] = 'value3';
associativeArray['key4'] = 'value4';
associativeArray['key5'] = 'value5';

var value = 'value3';
for(var key in associativeArray)
{
    if(associativeArray[key]==value)
         console.log(key);
}

Without loops (assuming a modern browser):

foundKeys = Object.keys(associativeArray).filter(function(key) {
    return associativeArray[key] == value;
})

returns an array of keys that contain the given value.

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

4 Comments

What if I want to delete 'key3' from this array? the splice function takes first parameter as index which must be an integer.
@gmuhammad The splice() method only operates on arrays, not objects. You will need to remove the property using delete associativeArray['key3'], for example.
thg435: You probably caused a bit of confusion by using the word 'array' in your variable name. Perhaps associativeMap might have been better to make clear it is an object, not an array?
@thg435, and GregL: Thank you very much both of you, GregL, you are right, I was confused and want this array to be treated as traditional array. But now I am clear. :)
2

If you don't use jQuery, you could extend the prototype of Object doing this:

// Returns the index of the value if it exists, or undefined if not
Object.defineProperty(Object.prototype, "associativeIndexOf", { 
    value: function(value) {
        for (var key in this) if (this[key] == value) return key;
        return undefined;
    }
});

Using this way instead of the common Object.prototype.associativeIndexOf = ... will work with jQuery if you use it.

And then you could use it like this:

var myArray = {...};
var index = myArray.associativeIndexOf(value);

It will also work with normal arrays: [...], so you could use it instead of indexOf too.

Remember to use the triple-character operators to check if it's undefined:

index === undefined // to check the value/index exists    
index !== undefined // to check the value/index does not exist

Of course you could change the name of the function if you prefer to for example keyOf, and remember not to declare any variable called 'undefined'.

Comments

1
let elementIndex = -1;

array.forEach((element, index, array) => {
   if (element["key"] == "someValue") {
      elementIndex = index;
   }
});

TypeScript Style:

let elementIndex = -1;

this.array.forEach((element, index, array) => {
   if (element.key. == "someValue") {
      elementIndex = index;
   }
});

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.