
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements