1

So I'm trying to compare the keys of two maps. The code below is syntactically valid; however, it returns false even though the keys of the two maps are similar. What could be the problem here?

const sc = new Map ();
sc.set ("item1",1)
sc.set ("item2",1)
sc.set ("item3",2)
sc.set ("item4",1) //ounce per serving //

const ing = new Map();
ing.set ("item1",1)
ing.set ("item2",1)
ing.set ("item3",2)
ing.set ("item4",1) //ounce per serving //

function compareMaps (map1,map2) {
if (ing.keys() == sc.keys() && (ing.size == sc.size)) {
    return "true"
} 
    return "false"

} 

compareMaps(ing, sc)
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • 4
    `img.keys() == sc.keys()` this is always going to be false, as they are two different objects (albeit with the same values). https://stackoverflow.com/questions/5703609/what-is-the-difference-between-being-shallowly-and-deeply-equal-how-is-this-app – ControlAltDel Aug 18 '20 at 16:33
  • https://stackoverflow.com/questions/35948335/how-can-i-check-if-two-map-objects-are-equal#:~:text=First%20check%20the%20.,its%20values%20to%20the%20other. – epascarello Aug 18 '20 at 16:35
  • Yeah, I suspected that as a problem. Because (ing.size == sc.size) works fine. Do you have any suggestions on how I can compare the keys aside from the map size? – inforoverload Aug 18 '20 at 16:35

3 Answers3

3

You could check Map#size of both maps and take the key in an array and check against with Map#has.

const sc = new Map();
sc.set("item1", 1)
sc.set("item2", 1)
sc.set("item3", 2)
sc.set("item4", 1) //ounce per serving //

const ing = new Map();
ing.set("item1", 1)
ing.set("item2", 1)
ing.set("item3", 2)
ing.set("item4", 1) //ounce per serving //

function compareMaps(map1, map2) {
    return map1.size === map2.size && [...ing.keys()].every(Map.prototype.has, map2);
}

console.log(compareMaps(ing, sc));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Your ing.keys() == sc.keys() comparison is flawed.

The Map.prototype.keys() method returns an Iterator to an object containing all keys of the Map (sorted in insertion order). Since ing.keys() and sc.keys() are returning separate objects, even if they may have identical keys, a comparison of the two values will always return false.

zcoop98
  • 2,590
  • 1
  • 18
  • 31
0

The keys() method is returning separate array objects. Although all of the elements within them are the same, they are two separate objects, and are therefore not equal.

What you need is a deep equal, which is something you can write yourself or bring in a dependency for, like UnderscoreJS. They have a lovely isEqual() function which does a deep comparison for you.

Kevin Hoopes
  • 477
  • 2
  • 8