0

i use hashmap in order to store the key value pair of the map.Please suggest me if their is an alternative way to do the same using NOdejs.

var HashMap=require('hashmap');
var map=new HashMap();
map.set("amit",[1,2]);
map.set("amit",[3,4]);
console.log(map.get("amit"));

On console it print [3,4], i want [1,2,3,4]. How am i going to approach this. if value in the value variable repeated then i also want to increase the count of the value corresponding to the same key.

2 Answers 2

1

You are overwriting the amit keys value every time you call set on that key. Unless there is some specific API support in hashmap, your best bet is to concatenate the previous value on every set call.

Consider:

var HashMap = require("hashmap")

var map = new HashMap()
map.set('amit', [1,2])
// Concat previous value with [3, 4]
map.set('amit', map.get('amit').concat([3,4]))

console.log(map.get('amit'))
// [1, 2, 3, 4]

You could also make an abstraction for this. The following is a simple example, you would most likely want to extend it further in a real use-case.

// concatSet('foo', [1, 2])
// concatSet('foo', [3, 4])
// console.log(map.get('foo')) => [1, 2, 3, 4]
function concatSet(key, value) {
   // empty array if not exists
   var prevValue = map.get(key) || []
   return map.set(key, prevValue.concat(value))
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank You. one more question if once again somebody enter map.set("amit",[1,4,5]); then is their a way to tell 1 enter two times.
No problem. I'm not sure I understand your question. My assumption is [1, 4, 5] should be [1,1,4,5]?
0

You have to loop the map.

map.set(1, "test 1");
map.set(2, "test 2");
map.set(3, "test 3");

map.forEach(function(value, key) {
    console.log(key + " : " + value);
});

https://www.npmjs.com/package/hashmap

1 Comment

my question is when key is same.

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.