How can I map multiple keys to the same value in JavaScript?

0
0
Asked By MellowCedar42 On

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

Answered By QuietOrbit7 On

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;
}
```

Answered By SilverPiano6 On

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.

Answered By AmberNoodle18 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.