0

I wanted to generate dictionary like below

a = {'A' => [1,2,3], 'B' => [12,13], 'C' => [32,432]}

var h = {}
gen_h(['A', 1])
gen_h(['A', 2])
gen_h(['B', 13])
gen_h(['C', 32])
gen_h(['C', 432])

should give h value as -

h = {'A' => [1,2], 'B' => [13], 'C' => [32,432]}
4
  • 2
    function gen_h(['A', 1])? Shouldn't this just be gen_h(['A', 1])? Commented Mar 9, 2012 at 19:31
  • 1
    What does this have to do with jQuery? Commented Mar 9, 2012 at 19:35
  • Did you mean generating an object instead of generating hash? I would call a hash something generated by a hash function, like MD5. Also, what has a to do with all of this? Commented Mar 9, 2012 at 20:19
  • @FelixKling.. Sorry but i am looking for key value pair hash not MD5 hash Commented Mar 9, 2012 at 20:30

1 Answer 1

1

This is just normal JavaScript, nothing to do with jQuery.

function gen_h(data){
    var key = data[0], // key
        val = data[1]; // value
    if(!h[key]){       // does hash exist?
        h[key] = [];
    }
    h[key].push(val);  // add value
}

Then you can do:

var h = {};
gen_h(['A', 1]);
gen_h(['A', 2]);
gen_h(['B', 13]);
gen_h(['C', 32]);
gen_h(['C', 432]);
Sign up to request clarification or add additional context in comments.

Comments

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.