JavaScript Hashmap Equivalent

JavaScript hashmap equivalent

Hash your objects yourself manually, and use the resulting strings as keys for a regular JavaScript dictionary. After all, you are in the best position to know what makes your objects unique. That's what I do.

Example:

var key = function(obj){
// Some unique object-dependent key
return obj.totallyUniqueEmployeeIdKey; // Just an example
};

var dict = {};

dict[key(obj1)] = obj1;
dict[key(obj2)] = obj2;

This way you can control indexing done by JavaScript without heavy lifting of memory allocation, and overflow handling.

Of course, if you truly want the "industrial-grade solution", you can build a class parameterized by the key function, and with all the necessary API of the container, but … we use JavaScript, and trying to be simple and lightweight, so this functional solution is simple and fast.

The key function can be as simple as selecting right attributes of the object, e.g., a key, or a set of keys, which are already unique, a combination of keys, which are unique together, or as complex as using some cryptographic hashes like in DojoX encoding, or DojoX UUID. While the latter solutions may produce unique keys, personally I try to avoid them at all costs, especially, if I know what makes my objects unique.

Update in 2014: Answered back in 2008 this simple solution still requires more explanations. Let me clarify the idea in a Q&A form.

Your solution doesn't have a real hash. Where is it???

JavaScript is a high-level language. Its basic primitive (Object) includes a hash table to keep properties. This hash table is usually written in a low-level language for efficiency. Using a simple object with string keys we use an efficiently implemented hash table without any efforts on our part.

How do you know they use a hash?

There are three major ways to keep a collection of objects addressable by a key:

  • Unordered. In this case to retrieve an object by its key we have to go over all keys stopping when we find it. On average it will take n/2 comparisons.
  • Ordered.
    • Example #1: a sorted array — doing a binary search we will find our key after ~log2(n) comparisons on average. Much better.
    • Example #2: a tree. Again it'll be ~log(n) attempts.
  • Hash table. On average, it requires a constant time. Compare: O(n) vs. O(log n) vs. O(1). Boom.

Obviously JavaScript objects use hash tables in some form to handle general cases.

Do browser vendors really use hash tables???

Really.

  • Chrome/node.js/V8:
    JSObject. Look for
    NameDictionary and
    NameDictionaryShape with
    pertinent details in objects.cc
    and objects-inl.h.
  • Firefox/Gecko:
    JSObject,
    NativeObject, and
    PlainObject with pertinent details in
    jsobj.cpp and
    vm/NativeObject.cpp.

Do they handle collisions?

Yes. See above. If you found a collision on unequal strings, please do not hesitate to file a bug with a vendor.

So what is your idea?

If you want to hash an object, find what makes it unique and use it as a key. Do not try to calculate a real hash or emulate hash tables — it is already efficiently handled by the underlying JavaScript object.

Use this key with JavaScript's Object to leverage its built-in hash table while steering clear of possible clashes with default properties.

Examples to get you started:

  • If your objects include a unique user name — use it as a key.
  • If it includes a unique customer number — use it as a key.
    • If it includes unique government-issued numbers like US SSNs, or a passport number, and your system doesn't allow duplicates — use it as a key.
  • If a combination of fields is unique — use it as a key.
    • US state abbreviation + driver license number makes an excellent key.
    • Country abbreviation + passport number is an excellent key too.
  • Some function on fields, or a whole object, can return a unique value — use it as a key.

I used your suggestion and cached all objects using a user name. But some wise guy is named "toString", which is a built-in property! What should I do now?

Obviously, if it is even remotely possible that the resulting key will exclusively consists of Latin characters, you should do something about it. For example, add any non-Latin Unicode character you like at the beginning or at the end to un-clash with default properties: "#toString", "#MarySmith". If a composite key is used, separate key components using some kind of non-Latin delimiter: "name,city,state".

In general, this is the place where we have to be creative and select the easiest keys with given limitations (uniqueness, potential clashes with default properties).

Note: unique keys do not clash by definition, while potential hash clashes will be handled by the underlying Object.

Why don't you like industrial solutions?

IMHO, the best code is no code at all: it has no errors, requires no maintenance, easy to understand, and executes instantaneously. All "hash tables in JavaScript" I saw were >100 lines of code, and involved multiple objects. Compare it with: dict[key] = value.

Another point: is it even possible to beat a performance of a primordial object written in a low-level language, using JavaScript and the very same primordial objects to implement what is already implemented?

I still want to hash my objects without any keys!

We are in luck: ECMAScript 6 (released in June 2015) defines map and set.

Judging by the definition, they can use an object's address as a key, which makes objects instantly distinct without artificial keys. OTOH, two different, yet identical objects, will be mapped as distinct.

Comparison breakdown from MDN:

Objects are similar to Maps in that both let you set keys to values,
retrieve those values, delete keys, and detect whether something is
stored at a key. Because of this (and because there were no built-in
alternatives), Objects have been used as Maps historically; however,
there are important differences that make using a Map preferable in
certain cases:

  • The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
  • The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of
    insertion.
  • You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
  • A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion
    and iterating over them.
  • An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can
    be bypassed by using map = Object.create(null), but this is seldom
    done.
  • A Map may perform better in scenarios involving frequent addition and removal of key pairs.

How is a JavaScript hash map implemented?

every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

Is there a way to create hashmap in javascript and manipulate it like adding and deleting values

Yes, that's an associative array (var hash = new Object();)

//You can add in these ways:

hash.January='1';
hash['Feb']='2';

//For length:
console.log(Object.keys(hash).length)

//To fetch by key:
console.log(hash['Feb']) // '2'

//To fetch all:
for(var key in hash){
console.log('key is :' + key + ' and value is : '+ hash[key])
}

javascript's equivalent of java's Map.getKey()

var myMap = {"one": 1, "two": 2, "three": 3};

declare it as a global variable

function getKey(value){
var flag=false;
var keyVal;
for (key in myMap){
if (myMap[key] == value){
flag=true;
keyVal=key;
break;
}
}
if(flag){
return keyVal;
}
else{
return false;
}
}

I dont think you need any function to get the value of a specific key.

You just have to write

var value = myMap[key];

How to create a simple map using JavaScript/JQuery

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
return map[k];
}

//map[myKey1] == get(myKey1);

.map equivalent of .forEach to create an object

You can combine Object.fromEntries and map methods. With map you can get array of [key, value] pairs and then by calling fromEntries you get an object from that array.

const keys = ['one', 'two', 'three'];
const result = Object.fromEntries(keys.map(k => ([k, ''])))
console.log(result)

How can I create HashMap in a JS file (in JQM)

In plain Javascript it is possible to create something very similar to a java HashMap:

var hashmap = {};

Put something in it:

hashmap['key'] = 'value';

Get something out of it:

var value = hashmap['key'];

For most purposes this will do, but it is not exactly the same as a hashmap, see for example this question:
JavaScript Hashmap Equivalent

Is there equivalent to C++ `unordered_map` in javascript

The equivalent of a JavaScript Map is the C++ unordered_map, as it provides sub-linear access (i.e. possibly logarithmic but constant in practice) and does not sort its keys. It keeps insertion order of elements for deterministic execution and cross-implementation compatibility, but it is not sorted.

There is no equivalent of the C++ map, which is implemented as a tree with comparable keys, in JavaScript.



Related Topics



Leave a reply



Submit