Hash Table/Hash Map in JS

In JavaScript the hash is already implemented, so there is no need to code your own. It can be done with Objects or Maps. For this blog I am going to go deeper into Map.

Map holds key-value pairs.

For us to start adding anything into our map we need to save an instance of the map in a variable.

const map = new Map()

Currently our map object is empty. Below I will show you the different things we can do with our map Object, and what the Big O notation is.

To ADD value into the map. O(1)(notice how I made my value into an array to push values to it later) You don’t need this if you don’t need to push.

map.set('key1', '[value1]') 

To RETRIEVE value from map O(1)

map.get('key1')

To DELETE value from map O(1)

map.delete('key1')

To get the SIZE of the map

map.size

To PUSH value to an established key-value pair

map.get('key1').push('value2')

To CHECK if a key is already present

map.has('key1')

To RETURN the list of keys that have a value greater than 1

return [...map.values()].filter(m => m.length > 1)

There are a couple more methods you can use with Map but this is a good start to be able to solve more problems. I also suggest to visit the MDN Web Docs for Map in JS.

I hope this was helpful to get a clearer view on the Hash Map. I was extremely confused at the beginning because I though you have to create your own. Fortunately, JS makes it easier on us.