Dinero
Dinero

Reputation: 1160

Using tuple as a key in a dictionary in javascript

In python I have a Random dictionary where I use tuple as a key and each is mapped to some value.

Sample

Random_Dict = {
    (4, 2): 1,
    (2, 1): 3,
    (2, 0): 7,
    (1, 0): 8
}

example in above key: (4,2) value: 1

I am attempting to replicate this in Javascript world

This is what I came up with

const randomKeys = [[4, 2], [2, 1], [2, 0], [1, 0] ]

const randomMap = {}

randomMap[randomKeys[0]] = 1
randomMap[randomKeys[1]] = 3
randomMap[randomKeys[2]] = 7
randomMap[randomKeys[3]] = 8
randomMap[[1, 2]] = 3

I am wondering if this is the most effective way. I almost wonder if i should do something like holding two numbers in one variable so that way i can have a dictionary in JS that maps 1:1. Looking for suggestions and solutions that are better

Upvotes: 8

Views: 3396

Answers (2)

JJWesterkamp
JJWesterkamp

Reputation: 7916

You can use a Map to map sets of 2 arbitrary values. In the following snippet the keys can be 'tuples' (1), or any other data type, and the values can be as well:

const values = [
  [ [4, 2], 1],
  [ [2, 1], 3],
  [ [2, 0], 7],
  [ [1, 0], 9],
];

const map = new Map(values);


// Get the number corresponding a specific 'tuple'
console.log(
  map.get(values[0][0]) // should log 1
);

// Another try:
console.log(
  map.get(values[2][0]) // should log 7
);

Note that the key equality check is done by reference, not by value equivalence. So the following logs undefined for the above example, although the given 'key' is also an array of the shape [4, 2] just like one of the Map keys:

console.log(map.get([4, 2]));

(1) Tuples don't technically exist in Javascript. The closest thing is an array with 2 values, as I used in my example.

Upvotes: 5

Alireza HI
Alireza HI

Reputation: 1933

You can do it this way:

const randomKeys = {
    [[4, 2]]: 1,
    [[2, 1]]: 3,
    [[2, 0]]: 7,
    [[1, 0]]: 8
}
console.log(randomKeys[ [4,2] ]) // 1 

[] in objects property is used for dynamic property assigning. So you can put an array in it. So your property will become like [ [4,2] ] and your object key is [4,2].

Upvotes: 4

Related Questions