4

In python, I can use tuples as the key to a dictionary. What's the equivalent in javascript?

>>> d = {}
>>> d[(1,2)] = 5
>>> d[(2,1)] = 6
>>> d
{(1, 2): 5, (2, 1): 6}

For those who are interested, I have two arrays...

positions = ...

normals = ...

I need to make a third array of position/normal pairs, but don't want to have duplicate pairs. My associative array would let me check to see if I have an existing [(posIdx,normalIdx)] pair to reuse or create one if I don't.

I need some way of indexing using a two-value key. I could just use a string, but that seems a bit slower than two numbers.

4
  • There isn't really one currently (an upcoming version of JavaScript is slated to include one) -- is there any particular reason to do so? Commented Mar 2, 2014 at 3:44
  • What are you trying to do exactly? I mean, you could actually use a string representation of your tuple as a key to the array, but the thought of it is kind of painful. You could also use an actual 2 dimensional associative array as well as Stepan mentions in his answer. I think you'll get a better answer if you say what you are trying to do, and maybe show how you are using the above sort of datastructures. Commented Mar 2, 2014 at 3:50
  • Can there be multiple normals for any one position or vice versa? Commented Mar 2, 2014 at 3:56
  • @Jack yes, this is exactly the reason why I need the two-value key. My application needs position/normals on a 1 to 1 ratio, but the data gets bigger if I don't reuse existing pairs. Commented Mar 2, 2014 at 4:09

2 Answers 2

5

Javascript does not have tuples but you can use arrays instead.

>>> d = {}
>>> d[[1,2]] = 5
>>> d[[2,1]] = 6
>>> d
Object {1,2: 5, 2,1: 6}
Sign up to request clarification or add additional context in comments.

1 Comment

Note this just uses the string representation of the array, that is, d['1,2'] is the same as d[[1,2]].
1

You can use a Map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.

This will avoid a potential problem with the key just being a string representation of the array.

d = {};
d[[1,2]] = 5;
d[[2,1]] = 6;
console.log("d[[1,2]]:", d[[1,2]]);
console.log("d['1,2']:", d['1,2']);

m = new Map();
ak1 = [1,2];
ak2 = [1,2];
m.set([1,2], 5);
m.set([2,1], 6);
m.set(ak1, 7);
console.log("m.get('1,2'):", m.get('1,2'));
console.log("m.get([1,2]):", m.get([1,2]));
console.log('m.get(ak1):', m.get(ak1));
console.log('m.get(ak2):', m.get(ak2));

Note that it uses a variable reference for the key, not the value.

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.