How to do associative array/hashing in JavaScript
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 = {};
JavaScript allows you to add properties to objects by using the following syntax:
Object.yourProperty = value;
An alternate syntax for the same is:
Object["yourProperty"] = value;
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
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 */
}
How to create an associative array in JavaScript literal notation
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200;
is identical to myArray.a = 200;
!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array
will return false
, because myObj
is not an ancestor from Array
in the prototype chain.
Do associative arrays perform like a hash table?
It's implemented differently in different javascript engines, and nowadays, it seems, objects aren't backed by "dictionary-like" data structures.
From https://developers.google.com/v8/design:
JavaScript is a dynamic programming language: properties can be added to, and deleted from, objects on the fly. This means an object's properties are likely to change. Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.
To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes. This basic idea is not new - the prototype-based programming language Self used maps to do something similar. In V8, an object changes its hidden class when a new property is added.
Firefox's IonMonkey does something similar. From an interview with a developer at Mozilla (http://www.infoq.com/news/2011/05/ionmonkey):
Dynamic languages probably don't have any inherent optimization advantages, but they do have interesting optimizations that static languages don't. For example, when you're writing JavaScript, objects appear to the user as hash tables, mapping property names to values. If they were actually implemented like that, they would be slow and use a lot of memory.
A good engine is able to internally group objects that look the same, sort of extracting an internal Java-like class out of them. The JIT can then treat the object as having an actual type, generating super fast code that avoids an expensive property lookup.
Creating some associative array in JavaScript
JavaScript doesn't have "associative arrays".
It has objects, which you can store values on in named properties.
It has arrays, which store an ordered set of values via integer properties. Since they are a type of object, you can also store named values on them (but you can't create them using the literal syntax, only add them after the array is created) but this isn't considered good practise and they will be ignored by just about anything that has special case handling for arrays.
As of ES6 it also has Maps which are similar to objects in that you can give them named values, but also to arrays in that order is preserved. There is no literal syntax for creating a Map.
Creating an associative array in JavaScript
You can have an array of objects containing key-value pairs, like this:
var per_kg_list = [
{'03749': '3.000'},
{'03750': '4.000'},
{'03751': '5.000'}
];
Alternatively, you can have an object containing key-value pairs, like this:
var per_kg_list = {
'03749': '3.000',
'03750': '4.000',
'03751': '5.000'
};
Search an associate array / hash in Javascript
You can do:
var target = "production";
var result = $.grep(data, function(e){ return e.target == target; });
console.log(result);
What kind of hashing function/algorithm does javascript associative array use?
Since V8 is open source, you go to the source:
Here's GetHash(): https://github.com/v8/v8/blob/master/src/objects.cc#L903
And, here's are some of the hash functions for different types: https://github.com/v8/v8-git-mirror/blob/bda7fb22465fc36d99b4053f0ef60cfaa8441209/src/utils.h#L347
And, this looks like the core hash computation for strings: https://code.google.com/p/v8/source/browse/trunk/src/objects.cc?spec=svn6&r=6#3574
uint32_t String::ComputeHashCode(unibrow::CharacterStream* buffer,
int length) {
// Large string (please note large strings cannot be an array index).
if (length > kMaxMediumStringSize) return HashField(length, false);
// Note: the Jenkins one-at-a-time hash function
uint32_t hash = 0;
while (buffer->has_more()) {
uc32 r = buffer->GetNext();
hash += r;
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
// Short string.
if (length <= kMaxShortStringSize) {
// Make hash value consistent with value returned from String::Hash.
buffer->Rewind();
uint32_t index;
hash = HashField(hash, ComputeArrayIndex(buffer, &index, length));
hash = (hash & 0x00FFFFFF) | (length << kShortLengthShift);
return hash;
}
// Medium string (please note medium strings cannot be an array index).
ASSERT(length <= kMaxMediumStringSize);
// Make hash value consistent with value returned from String::Hash.
hash = HashField(hash, false);
hash = (hash & 0x0000FFFF) | (length << kMediumLengthShift);
return hash;
}
It's probably worth mentioning that V8 goes to great lengths to avoid using a hash table for object properties whenever possible, preferring to compile known property references into direct index references rather than run-time hash lookups for performance reasons (though this is only possible sometimes - depends upon the code).
Making an associative array in Javascript that has custom get/put operations
I decided that the most correct way to implement this is to use Harmony:Proxies. It isn't working on all platforms, but it lets implement this in the most seamless way; and it may be supported in more platforms in the future.
This page contains an example that I used as a template to do what I want:
http://wiki.ecmascript.org/doku.php?id=harmony:proxies
Creating an associative array using JavaScript
Didn't it occur to you that JavaScript isn't PHP?
This is simply not the correct syntax.
Use:
var cst_dta = {
'name' : 'amar',
'total_bill' : 'akbar',
'phone' : 'anthony'
};
You have much more details on object literals (and other literals) on this page.
Related Topics
How to Add Conditional Attribute in Angular 2
How Does the (Function() {})() Construct Work and Why Do People Use It
When Does Js Interpret {} as an Empty Block Instead of an Empty Object
Parse JSON String into a Particular Object Prototype in JavaScript
How to Import Es6 Modules in Content Script for Chrome Extension
JavaScript - How to Show Escape Characters in a String
Why Should I Use a Semicolon After Every Function in JavaScript
JavaScript Print Iframe Contents Only
String.Replace' Weird Behavior When Using Dollar Sign ($) as Replacement
Parallel Asynchronous Ajax Requests Using Jquery
How to Get the Fragment Identifier (Value After Hash #) from a Url
Accessing Variables from Greasemonkey to Page & Vice Versa
How to Get the (X, Y) Pixel Coordinates of the Caret in Text Boxes
Stoppropagation VS. Stopimmediatepropagation