How can I check if two Map objects are equal?

Viewed 57653

How can I check if two ES2015 Map objects have the same set of (key, value) pairs?

We can assume that all the keys and values are primitive datatypes.

One approach to solve this would be to take the map.entries(), create array from it, then sort that array by keys. And do the same thing with the other map. And then loop through those two arrays to compare them. All this seams cumbersome and also very inefficient because of sorting (performance inefficiency) and because of making those arrays (memory inefficiency).

Does anybody have better idea?

5 Answers

The above won't work for Map<string, object> as in the following line will not evaluate two objects properly:

if (testVal !== val || (testVal === undefined && !map2.has(key))) {

The following version extends the function for Map<string, object> by comparing using JSON.stringify()

function compareMaps(map1, map2) {
    var testVal;
    if (map1.size !== map2.size) {
        return false;
    }
    for (var [key, val] of map1) {
        testVal = map2.get(key);
        // in cases of an undefined value, make sure the key
        // actually exists on the object so there are no false positives
        if (JSON.stringify(testVal) !== JSON.stringify(val) || (testVal === undefined && !map2.has(key))) {
            return false;
        }
    }
    return true;
}

Here's a one-liner function for checking map equality:

const mapsAreEqual = (m1, m2) => m1.size === m2.size && Array.from(m1.keys()).every((key) => m1.get(key) === m2.get(key));
Related