0

I am using a two-dimensional array in some code which I would like to replace with a more suitable data structure in context, namely a Map. I would like to use the Map methods, also hope that the performance will improve that way. However, I run into the following problem:

const myMap = new Map();
myMap.set([1,2],"some value");
console.log(myMap.get([1,2]));

This returns undefined. I kind of understand why this is the case, but it is inconvenient. The following works, but it cannot be used in practice. (Imagine that I want to check the map at some coordinate which results from some computation, it just cannot refer to the same coordinate where the Map was set.)

const myMap = new Map();
const someCoord = [1,2];
myMap.set(someCoord,"some value");
console.log(myMap.get(someCoord));

Are there any workarounds for this? Or are maps not suitable for this kind of implementation of two-dimensional arrays?

3
  • 1
    You could stringify the array, and then use that as the key. Commented Apr 7, 2020 at 7:52
  • 1
    This is an interesting workaround, thank you! Commented Apr 7, 2020 at 7:53
  • If you were to stringify the array (JSON.stringify or Array#join) you could also use plain objects instead of maps Commented Apr 7, 2020 at 7:55

1 Answer 1

1

Two different object can never evaluate as true using comparison, you can use strings as key instead of array

const myMap = new Map();
myMap.set([1, 2].toString(), "some value");
console.log(myMap.get([1, 2].toString()));

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

Comments

Your Answer

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