Search Element in a Dictionary using Javascript

Web DevelopmentFront End TechnologyJavascript

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
raja
Published on 27-Jun-2018 17:14:51
Advertisements