i want to ask if it's possible to do this:
const map1 = new Map();
map1.set('1', "led");
map1.set('2', "zeppelin");
const map2 = new Map();
map2.set('1', "led");
map2.set('2', "floyd");
I want to compare these 2 maps. I want to have a console.log() with the deferences of the maps.
Finally if the maps are the same and i add in map1 a new set
map1.set('3', "plant");
I want a log to tell me which is the new pair of kay-val
Thank you
const map1 = new Map();
map1.set('1', "led");
map1.set('2', "zeppelin");
const map2 = new Map();
map2.set('1', "led");
map2.set('2', "floyd");
let isSame = true;
map1.forEach(function(val, key){
if(map2.get(key) != val){
console.log('map1.'+key+' = '+val +' | map2.' + key + ' =
'+map2.get(key));
isSame = false;
}
})
if(isSame){
map1.set('3', "plant");
map1.forEach(function(val, key){
console.log('map1.'+key+' => '+val);
})
}
Here another solution using Map#entries() and Array#every().
This solutions checks that the supplied parameters are actually Maps and immediately returns false if the size does not match. Only if all those checks are passed an actual comparison of each key and value within the Map is performed which will greatly improved the amortized runtime. In worst case the runtime will be O(n) with n being the number of key-value pairs in map1.
Comparison of keys and values is done on basis of strict equality meaning that no deep comparison of arrays or objects is done. One could use lodash#isEqual() if that is a requirement. For the given example that is not necessary.
const map1 = new Map();
map1.set("1", "led");
map1.set("2", "zeppelin");
const map2 = new Map();
map2.set("1", "led");
map2.set("2", "floyd");
const map3 = new Map();
map3.set("1", "led");
map3.set("2", "zeppelin");
function areEqual(map1, map2) {
// early outs
if(!(map1 instanceof Map) || !(map2 instanceof Map) || map1.size !== map2.size) return false;
// we know we have to maps with the same amount of keys and values. Now compare them
return [...map1.entries()].every(([key, value]) => (map2.has(key) && map2.get(key) === value));
}
console.log(areEqual(map1, map2));
console.log(areEqual(map1, map3));