1

I'm trying to create a map based on certain arrays of three. For example,

const rule30Map = new Map();
rule30Map.set([1, 0, 0], 1);
rule30Map.set([0, 1, 1], 1);
rule30Map.set([0, 1, 0], 1);
rule30Map.set([0, 0, 1], 1);

When I try getting a value based on values in an array, the console returns undefined,

console.log(rule30Map.get([1, 0, 0])); // prints undefined

but the expected output would be 1. Can somebody explain why my logic was misunderstood?

2
  • 2
    Non-primitives are compared by reference, not by value. Keep in mind in JS [1] === [1] is false. Commented Jul 19, 2021 at 13:56
  • That means that setting map keys using non-primitive literals will result in a map with inaccessible keys because obviously you cannot have a reference to these literals. Commented Jul 19, 2021 at 14:02

2 Answers 2

2

The keys are compared with === comparison. Two separate arrays that look like [1, 0, 0] are still two separate arrays that are not equal to each other.

Working out some automated way of keeping track of key objects by their characteristics somehow would probably be more complicated than using a plain object for storage. Because JavaScript does not provide a generic way for a class of objects to supply hashing and comparison overrides means that Map and Set in JavaScript are somewhat limited in usefulness.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for explaining this! Would there be a correct way of doing what I am trying to achieve, then?
@Daniel well if there aren't a crazy number of key objects, you could keep them as named constants or named properties in some object.
Nitpick: keys are compared with SameValueZero, not with ===, so new Map([ [ NaN, 1 ] ]).get(NaN) === 1.
@SebastianSimon yes I know; I didn't want to muddle up the simple basic explanation with that kind of arcana :) It is of course important to know it however.
The records and tuples proposal will allow new Map([ [ #[ 1, 0, 0 ], 1 ] ]).get(#[ 1, 0, 0 ]) === 1.
|
1

You could do:

const a = [1,0,0];
const map = new Map();
map.set(a.toString(), "value");

map.get([1,0,0].toString());

I assume you are computing the [1,0,0] part.

2 Comments

Converting every key to a string loses the benefits of Map.
Ok, but I think it is sufficient to work with, look at other questions like this one: stackoverflow.com/questions/61231359/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.