Sunday, 21 October 2018

JavaScript: Map: delete: Delete an entry from map

Map.prototype.delete(key)
Removes the mapping for the specified key from this map if present. This method returns true, if the element exists in the map and removed, else false.

HelloWorld.js
function printMap(map){
  console.log("***************************");
  console.log("Total elements in countriesMap are : " + map.size);
  for (var [country, capital] of map) {
    console.log(country + ' : ' + capital);
  }
  console.log("***************************");
}

var countriesMap = new Map();

countriesMap.set("Bahrain", "Manama");
countriesMap.set("Cameroon", "Yaounde");
countriesMap.set("Norway", "Oslo");
countriesMap.set("India", "New Delhi");
countriesMap.set("Russia", "Moscow");
countriesMap.set("Spain", "Madrid");

printMap(countriesMap);

console.log("\nDeleting the keys 'Spain', 'Cameroon', 'India'\n");

countriesMap.delete("Spain");
countriesMap.delete("Cameroon");
countriesMap.delete("India");

printMap(countriesMap);


Output
***************************
Total elements in countriesMap are : 6
Bahrain : Manama
Cameroon : Yaounde
Norway : Oslo
India : New Delhi
Russia : Moscow
Spain : Madrid
***************************

Deleting the keys 'Spain', 'Cameroon', 'India'

***************************
Total elements in countriesMap are : 3
Bahrain : Manama
Norway : Oslo
Russia : Moscow
***************************



Previous                                                 Next                                                 Home

No comments:

Post a Comment