Javascript – How to use array as key in Javascript


I have a simple example on python:

programs = {}
if not programs.has_key(( program, time )):
     programs[( program, time )] = 0
programs[( program, time )] = programs[( program, time )] + 1

How to use array as key in Javascript ?

Best Solution

This will "work". (but I don't recommend it)

var a = {};
var b = [1,2,3];    
a[b] = 'hello';

// a[b] evaluates to 'hello'
// a[[1,2,3]] evaluates to 'hello'
// a['1,2,3'] evaluates to 'hello'

It works because when you pass the array [1,2,3] as the hash (map/associative-array) key, is being converted to the string '1,2,3' before performing the hash lookup. It should suit your needs as long as you don't need two different arrays of the same value to map to different hash values.

var c = [1,2,3]
// a[c] evaluates to 'hello' even though we never executed a[c] = 'hello'
// but b == c evaluates to false
// b & c are two separate objects with the same values, so when they
// get converted to a string for hashing, they return the same value from the hash

As it was mentioned, you'll need more than the standard JavaScript hash if you want to use object references as your keys.


Based on the comment from @speedplane:

I suspect that JS calls toString() on the array when you pass it into a hash key. So you can easily test what you're actually going to get as your key:

 ["x", "y", "z"].toString();                // 'x,y,z'
 ["x,y,z"].toString();                    // 'x,y,z'
 [1,2,3].toString();                      // '1,2,3'
 [1,2,'3'].toString();                    // '1,2,3'
 [[1],[2],[3]].toString();                // '1,2,3'
 [["x",1], ["y",2], ["z",3]].toString();  // 'x,1,y,2,z,3'

So again, I recommend that you don't do this unless you really understand what is going on. And even then, I wouldn't do it.