3

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?

14
  • The example you provided is not a valid Object. Please explain in more detail what you are trying to achieve. Commented Oct 3, 2013 at 1:44
  • This looks like a XY problem. Please tell us what you need that for. Also, please show us the code you've tried, this should be a fairly trivial task. Commented Oct 3, 2013 at 1:47
  • basically, I want to store a key value table that has a key (the length of the word), and a value (an array of the words that are anagrams). I want to be able to go through the hash map that I have and add values to this new table Commented Oct 3, 2013 at 1:49
  • Ah I see, you're storing the word and an anagram of the word. Is that correct? Commented Oct 3, 2013 at 1:49
  • I'm storing the word, and the alphabetically sorted version of that word Commented Oct 3, 2013 at 1:50

1 Answer 1

2

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] ];
}
Sign up to request clarification or add additional context in comments.

5 Comments

What would the javascript code look like for storing an array of strings for each key?
Have you tried anything yourself? Just put an array as each value, and push to it when it already exists.
hash2 = {}; var count = 0; for (i in hash1){ for (j in hash1){ if (i!=j && hash1[i] == hash1[j]) console.log("match!"); hash2[count].push(hash1[i]); } count++; }
Oops, sorry that looks terrible
@ZachLucas: You might put the code into your question as well. Please also include there how you're constructing hash1

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.