Zach Lucas
Zach Lucas

Reputation: 1641

How can I store multiple values per key in a hash table using Node.JS?

In javascript, I have a hash map of key value pairs like:

"team", "aemt"
"meat", "aemt"
"car", "acr"

And I want to store all of the matching values with the length of the string like this:

{4, {"team","meat"}}
{3, {"car"}

How would I accomplish this?

Upvotes: 3

Views: 18474

Answers (1)

Bergi
Bergi

Reputation: 664936

Dividing your sets by length should not be necessary, the hashing algorithm should be able to take care of that itself. It would only be advisable if you're going to sort your words by length.

store multiple values per key in a hash table

You cannot. However, you can store an array of strings for each key.

var words = ["team", "meat", "car"],
    map = {};
for (var i=0; i<words.length; i++) {
    var key = words[i].toLowercase().split('').sort().join('');
    if (key in map)
        map[key].push(words[i]);
    else
        map[key] = [ words[i] ];
}

Upvotes: 2

Related Questions