How can I map multiple keys to the same value in JavaScript?
Asked by
MellowCedar42
I'm building a small helper where several keys should point to the same value. For example, 1, 2, and 3 should all retrieve the function associated with the group [1, 2, 3]. I initially represented each group as an array and wondered whether arrays could be used as hashable dictionary keys. Is there a clean way to implement this with Map, without relying on tuples?
```js
const map = MapFactory([
[[1, 2, 3], () => "1-3"],
[[4, 5, 6], () => "4-6"],
[[7, 8, 9], () => "7-9"]
]);
console.log(map.get(1)()); // "1-3"
console.log(map.get(6)()); // "4-6"
```
Answers
You can create the same map directly with `flatMap`:
```js
const map = new Map([
[[1, 2, 3], () => "1-3"],
[[4, 5, 6], () => "4-6"],
[[7, 8, 9], () => "7-9"]
].flatMap(([keys, value]) =>
keys.map(key => [key, value])
));
```
This produces entries such as `[1, fn]`, `[2, fn]`, and `[3, fn]`, so `map.get(1)` works as intended.
Reply to this answer
If you actually need the entire array to be the key, serialization is one option:
```js
const map = new Map();
map.set(JSON.stringify([1, 2, 3]), "foo");
map.get(JSON.stringify([1, 2, 3])); // "foo"
```
A helper can hide the conversion. Just remember that array order matters, and serialization has edge cases for complex values. It also doesnโt solve the separate requirement of looking up an individual number; for that, storing one entry per number is simpler and more efficient.
Reply to this answer
You donโt need to make the array hashable for this use case. A Map can use arrays and other objects as keys, but it compares them by identity, so `[1, 2, 3]` and another separately created `[1, 2, 3]` are different keys. Since you want each individual number to retrieve the groupโs value, just insert one Map entry per number.
Also, the loops in the original code should be `for...of`, not `for...in`:
```js
function MapFactory(items) {
const map = new Map();
for (const [keys, value] of items) {
for (const key of keys) {
map.set(key, value);
}
}
return map;
}
```
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions