Skip to content
Advertisement

Compare 2 maps in JavaScript

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

Advertisement

Answer

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);
    })
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement