Search code examples
javascriptdictionarydata-structuresecmascript-6es6-map

How to check if two Maps have the same key set in JavaScript


Suppose to have two Map objects, how to check if their keys sets are the same?

For example:

const A = new Map();
A.set('x', 123);
A.set('y', 345);

const B = new Map();
B.set('y', 567);
B.set('x', 789);

const C = new Map();
C.set('x', 121);
C.set('y', 232);
C.set('z', 434);

in this case both A and B maps have the same key set (which is ['x', 'y']), while the key set of C is different since it has the extra key z.


Solution

  • You could check the size and then iterate over the keys of one map and check that the other one has them too.

    const A = new Map();
    A.set('x', 123);
    A.set('y', 345);
    
    const B = new Map();
    B.set('y', 567);
    B.set('x', 789);
    
    const C = new Map();
    C.set('x', 121);
    C.set('y', 232);
    C.set('z', 434);
    
    function sameKeys(a, b) {
      if (a.size != b.size) {
        return false;
      }
    
      for (let key in a.keys()) {
        if (!b.has(key)) {
          return false;
        }
      }
    
      return true;
    }
    
    console.log(sameKeys(A, B));
    console.log(sameKeys(A, C));