DEV Community

loading...
Cover image for How to do associative array hashing in Javascript ?

How to do associative array hashing in Javascript ?

courseprobe profile image Course Probe ・2 min read

Let’s say you are looking for a way to store some statistics like you would do in other languages like C# and you are wondering if there is a Hashtable or something like Dictionary in JavaScript which could serve the purpose.

Then, keep reading the below options and examples that might come handy for this scenario …

Use JavaScript objects as associative arrays.

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.

Create an object with

var dictionary = {};
Enter fullscreen mode Exit fullscreen mode

JavaScript allows you to add properties to objects by using the following syntax:

Object.yourProperty = value;
Enter fullscreen mode Exit fullscreen mode

An alternate syntax for the same is:

Object["yourProperty"] = value;
Enter fullscreen mode Exit fullscreen mode

If you can, also create key-to-value object maps with the following syntax:

var point = { x:3, y:2 };

point["x"] // returns 3
point.y // returns 2
Enter fullscreen mode Exit fullscreen mode

You can iterate through an associative array using the for..in loop construct as follows

for(var key in Object.keys(dict)){
  var value = dict[key];
  /* use key/value for intended purpose */
}
Enter fullscreen mode Exit fullscreen mode

All modern browsers support a JavaScript Map object. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.

  • The keys of an Object are Strings, where they can be any value for a Map.

  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"
Enter fullscreen mode Exit fullscreen mode

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

Resources you might find useful:

Get the book: Javascript Challenges

source: https://stackoverflow.com/questions/1208222/how-to-do-associative-array-hashing-in-javascript


Other Dev posts:

Discussion (0)

pic
Editor guide