0

I need an hash table in Javascript, i.e. to implement an associative array which maps keys (strings) to values (in my case, these are several integer arrays). I realized that this kind of approach is not commonly used, or at least I haven't found it on the web yet:

var hash = ['s0'];
for (var i = 5; i >= 1; i--) {
  var r = Math.floor(Math.random() * 3);
  hash['s'+i] = [r, r*2, r^2];
}
console.log(hash);
hash.forEach(function (v, i, a) {
  document.getElementById('foreach').innerHTML += i + ' => ' + v + '<br>';
})
for (var i = 5; i >= 1; i--) {
  var key = 's'+i;
  document.getElementById('for').innerHTML += key + ' => [' + hash[key].toString() + ']<br>';
}
<p id="foreach">forEach (val,index):<br/></p>
<p id="for">for:<br/></p>

Perhaps due to the fact that the declared array seems to not be correctly mapped after I add the new values (open your console and click the + button, you can see the values are there even when it displays [s1]). The forEach keeps assuming the array only has one value, but if I access any of those keys directly, e.g. hash['s3'], the respective array is returned.

Therefore, am I doing something wrong? Should I even use this approach?


If objects in JSON are more appropriate for this case, what is the best way to implement something simple and similar to the example above?

Furthermore, if key_string is the string I want as key, hash.push(key_string: val_array) fails because it is not a "formal parameter". However by doing something like:

hash.push({'key':key_string,'value':val_array})

How can I access one of those arrays in the simplest way possible through its associated key?

8
  • 1
    javascript object properties act about the same as a hash table or associative array, implementing a hash table in javascript is either the wrong way to solve whatever problem you are trying to solve, or a homework question. Commented Oct 3, 2016 at 17:54
  • change var hash=['s0'] to var hash = {'s0':'first_element'}; and see what it does Commented Oct 3, 2016 at 18:01
  • Thanks @chiliNUT, but if object properties "act about the same as an hash table" and if by "homework question" you are saying this is a "trivial question", would you kindly provide a simple alternative to the hash table problem? I am using a code similar to the above and it works for my purposes, but it is not a convenient thing to not be able to use forEach... Commented Oct 3, 2016 at 18:02
  • There's no such thing as a "JSON object", by the way, there's just JSON (which is a string) and object which is an Object... Commented Oct 3, 2016 at 18:04
  • Thanks @VladimirM, I have tried the Object approach, and if you notice the small letters at the end the question, using a dynamic key (key_string) has not worked for me. Commented Oct 3, 2016 at 18:04

3 Answers 3

1

Why can't you use a JavaScript Map()?

MDN JavaScript Reference: Map

I modified your code below to use a Map instead of an Array:

var map = new Map();
for (var i = 5; i >= 1; i--) {
  var r = Math.floor(Math.random() * 3);
  map.set('s'+i, [r, r*2, r^2]);
}
console.log(map);
map.forEach(function (v, i, m) {
  document.getElementById('foreach').innerHTML += i + ' => ' + v + '<br>';
})
for (var i = 5; i >= 1; i--) {
  var key = 's'+i;
  document.getElementById('for').innerHTML += key + ' => [' + map.get(key).toString() + ']<br>';
}
<p id="foreach">forEach (val,index):<br/></p>
<p id="for">for:<br/></p>

Sign up to request clarification or add additional context in comments.

1 Comment

Alright! I knew there was something I was missing! Truly appreciated.
1

Javascript's object type covers all the behavior you are looking for:

var obj = {};
for (var i = 5; i >= 1; i--) {
    var r = Math.floor(Math.random() * 3);
    obj['s'+i] = [r, r*2, r^2];
}

The cool thing about the object type in Javascript is you can access properties using the associate array-like syntax or using dot notation.

obj['key'] === obj.key

Comments

1

Please, check this example in the console.

var hash = {'s0':' '};
for (var i = 5; i >= 1; i--) {
  var r = Math.floor(Math.random() * 3);
  hash['s'+i] = [r, r*2, r^2];
}

see that hash object now contains key-value mapping

console.log(hash);

to access the object with forEach you can extract the keys of the object as an array and iterate over it:

Object.keys(hash).forEach(function (v, i, a) {
  console.log( i , v, hash[v] );
})

You may also start using such libraries as https://lodash.com/ that implement a number of common operations over collections.

1 Comment

Please add some explanation of why this code helps the OP. This will help provide an answer future viewers can learn from. See How to Answer for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.