inforoverload
inforoverload

Reputation: 57

Troubleshooting: comparing keys of two maps (Javascript)

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)

Upvotes: 1

Views: 575

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386654

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));

Upvotes: 3

Kevin Hoopes
Kevin Hoopes

Reputation: 507

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.

Upvotes: 0

zcoop98
zcoop98

Reputation: 3087

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.

Upvotes: 0

Related Questions