Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 903
Dinero Avatar asked Jun 23 '26 14:06

Dinero


2 Answers

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.

like image 67
JJWesterkamp Avatar answered Jun 25 '26 03:06

JJWesterkamp


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].

like image 45
Alireza HI Avatar answered Jun 25 '26 02:06

Alireza HI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!