I am looking for a way how we can implement HashMap functionality in javascript. I found map() as global object which has been introduced in es6 using which we can do the same.But making a a value as an array doesn't seems to be working.Can anyone help me for the same.
Map-JavaScript | MDN
Below is the snippet of the sample code.
var map1 = new Map();
var names=['abc','bcd','abc'];
for(var i=0;i<name.length;i++){
if(map1.has(name[i]))
map1.set(name[i],map1.get(name[i]).push('B'));//if key is already there append B
else
map1.set(name[i],['A']);//if key is not present append A
}
console.log(map1);
I am expecting the value of the key abc as ['A','B']
Actual Result :
Map { 'abc' => 2, 'bcd' => [ 'A' ] }
Expected Result :
Map { 'abc' => ['A','B'],'bcd' => ['A']}
.push()returns the new length of the array, not the array itself.map1.get(name[i]).push('B')and that result is the new length of the array. You don't need to assign anything - arrays in JS are actually like ArrayLists in Java and can grow normally. Also, since you're storing the array reference, any modifications to the array will be "shared" with the map where it's at. Since you're only modifying the same object. Just domap1.get(name[i]).push('B'))without doingmap.setat the same time.