Larry Steinle

October 9, 2013

JavaScript Hash Array (Dictionary)

Filed under: Web — Larry Steinle @ 10:15 pm
Tags: , , ,

A hash array (aka dictionary) stores a value in memory that is accessible using a key name. I like using hash arrays to store the key/value pairs found in an URL’s query string. JavaScript comes with a standard indexed array but lacks a hash array. Lucky for us creating a hash array is a very simple and useful exercise in JavaScript.

Before continuing I have to be honest and admit that I lied. JavaScript actually includes a built-in hash array. It is everywhere in JavaScript. You can’t have JavaScript without a hash array!

This post will demonstrate how to create a simple, effective hash array using JavaScript’s function array.

JavaScript Fundamentals

Every JavaScript class is a hash array. Allow me to demonstrate with a simple example. Let’s say we want to create a class in JavaScript. That’s simple enough as shown in our first code snippet.

var dogClass = function (breed) {
  this.breed = breed;
  this.bark = function () { alert('woof'); };
};

var blackLab = new dogClass("Lab");
blackLab.bark(); 

In our example we have created a dog class with a breed property and a bark function. We can create a new instance of our dog class and call the bark method. But did you know you can also call the bark method with the following code snippet?

var blackLab = new dogClass("Lab");
blackLab["bark"]();

We just referenced the function using a key name! Hey, wait a minute! That’s a hash! You mean to say that a class is a hash of function names and statement blocks? YEP! And, that’s what makes it so easy to create a hash array in JavaScript!

Strategy

In our custom hash array we will take advantage of the built-in function hash. This really simplifies our job. Before we begin let’s review the capabilities required from our hash array.

The hash array will provide the ability to:

  • Add a key/value pair to the hash.
  • Update an existing key with a new value.
  • Check the hash for a key.
  • Check the hash for a value.
  • Clear the hash.
  • Returns the hash as an indexed array.

The hash array will be built using a function with the required methods. The actual data will be stored in a hidden JSON object that will contain a property for each key with it’s value.

The Hash

I believe that after having explained how a function in JavaScript is actually a hash array that the code below will be very straight forward. Without further ado here is the code for a hash array!

var hashArray = function () {
  //Create JSON hash array.
  this.hash = {};

  this.add = function (key, value) {
    if (this.hash[key] === undefined)
      this.hash[key] = value;
  }

  this.clear = function () {
    this.hash = {};
  }

  this.get = function (key) {
    return this.hash[key];
  }

  this.set = function (key, value) {
    if (this.hash[key] !== undefined) 
      this.hash[key] = value;
  }

  this.containsKey = function (key) {
    return this.hash[key] !== undefined;
  }

  this.containsValue = function (value) {
    for (var i in this.hash)
      if (this.hash.hasOwnProperty(i) && this.hash[i] === value)
        return true;
    return false;
  };

  this.toArray = function () {
    var arr = [];
    for (var i in this.Hash)
      if (this.Hash.hasOwnProperty(i))
        arr.push([i, this.Hash[i]]);
    return arr;
  };
};

var dogs = new hashArray();
dogs.add("Lab", new dogClass("Lab"));
dogs.add("Poodle", new dogClass("Poodle"));

dogs.get("Lab").bark();

Summary

As you can see creating a JavaScript hash array is actually quite simple. I’m sure that you can already imagine additional helper functions to add to our sample hash array to make it more useful for your own purposes!

Happy coding!

Advertisements

2 Comments »

  1. Wow, this article is good, my younger sister is analyzing these kinds of things, therefore I am going
    to convey her.

    Comment by Derrick — June 6, 2014 @ 3:24 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: