- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search Element in a Dictionary using Javascript
We'll implement the get method that searches a given key in the dictionary.
Example
get(key) { if(this.hasKey(key)) { return this.container[key]; } return undefined; }
Again, JS objects are very much implemented like dictionaries, hence have most of the functionality we can use directly without any more code needed. This is also heavily optimized, so you don't have to worry about the runtime of the function.
You can test this using −
Example
const myMap = new MyMap(); myMap.put("key1", "value1"); myMap.put("key2", "value2"); console.log(myMap.get("key1")) console.log(myMap.get("key2")) console.log(myMap.get("key3"))
Output
This will give the output −
value1 value2 undefined
In ES6, you have the same functionality using the get method. For example,
Example
const myMap = new Map([ ["key1", "value1"], ["key2", "value2"] ]); console.log(myMap.get("key1")) console.log(myMap.get("key2"))
Output
This will give the output −
value1 value2
Advertisements