JavaScriptTutorials

JavaScript – Hash Maps

What are hash maps? How do you use them in JavaScript? This post will hopefully answer these questions.

It might be worth taking a minute to read the wikipedia article on hash maps here. But to summarize, a hash map is basically a way to map unique keys to values. It helps search and retrieve specific items from a list quicker and easier. Let’s look at an example.

Let’s say you have a long list of items, maybe thousands of customer names, and you must regularly be able to retrieve specific names from this list given a unique ID tied to each name. For example:

let arr = [
{ id: 87, name: 'Bob' },
{ id: 102, name: 'Jennifer' },
{ id: 132, name: 'Jacob' },
{ id: 243, name: 'John' },
{ id: 452, name: 'Patricia' },
{ id: 598, name: 'Alicia' },
{ id: 607, name: 'Jeff' }
];

Instead of only 7 items in the list, let’s imagine we have 7,000 items. Now, say we have a business requirement wherein we must be able to retrieve a customer name given it’s associated id. Let’s see how this function might look:

function getCustomerById (id) {
for(let i = 0;i < arr.length;i++) {
if (arr[i].id === id) return arr[i].name;
}

return 'No customer found at id: ' + id;
}

getCustomerById(598); // 'Alicia'

Not so bad right? Only 7 lines of code. However, notice we are looping through the entire list of items until we reach our desired customer at the given id. We are blindly starting from index 0, and iterating item by item. Not so efficient if you think about it. Let’s look at how a hash map can help with this.

How do you use them in JavaScript?

Same example as before. But let’s construct our list of customer names as a JavaScript object with unique keys (id’s), and values (customer names):

let map = {
87: 'Bob',
102: 'Jennifer',
132: 'Jacob',
243: 'John',
452: 'Patricia',
598: 'Alicia',
607: 'Jeff'
};

Okay, so now we have our same customer list, except instead of an array of objects, it’s simply an object, with the id’s as keys, and the customer names as values. If you need a primer on JavaScript objects, please see my JavaScript Objects tutorial here.

Same business requirements as above, we need to be able to retrieve customer names given their id. Let’s see how this functions looks now that we have a beautiful hash map:

function getCustomerById (id) {
return map[id] !== undefined ? map[id] : 'No customer found at id: ' + id;
}

getCustomerById(598); // 'Alicia'

Boom, just like that we have removed a pesky for loop along with 4 lines of code, and are still able to retrieve our customer name.

I hope this helps, and at least makes some sense. You can see a pen of it here.

Please, as always, also educate me on better ways to code in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *