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"
```
3 Answers
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;
}
```
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.
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.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically