Remove elements from a Dictionary using Javascript


To remove an element from the dictionary, we first need to check if it exists in the dictionary.

We'll use the hasKey method for that. Then we can directly delete it using the delete operator.

We'll return a Boolean so that the place where we call this method can know whether the key already existed or not in the dictionary. 

Example

delete(key) {
   if(this.hasKey(key)) {
      delete this.container[key];
      return true;
   }
   return false;
}

You can test this using − 

Example

const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

myMap.display(); myMap.delete("key2");

myMap.display();

Output

This will give the output −

{ key1: 'value1', key2: 'value2' }
{ key1: 'value1' }

In ES6, you have the delete method to remove values from the map. For example, 

Example

const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);
myMap.delete("key2");

console.log(myMap.has("key1"))
console.log(myMap.has("key2"))

Output

This will give the output −

True
False

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements