Skip to content
Advertisement

How to increase all values of a map in javascript

I have this map:

var map = new Map();

map.set("10/10", 0);
map.set("10/11", 1);
map.set("10/12", 2);

     
{
   "10/10": 0,
   "10/11": 1,
   "10/12": 2,
}

And I want to add this new key/value:

"10/9": 0,

How can I increase the values of all the old map elements in 1? So I get the following map:

{
   "10/9": 0,
   "10/10": 1,
   "10/11": 2,
   "10/12": 3,
}

Advertisement

Answer

You can use something like this:

var map = new Map();

map.set("10/10", 0);
map.set("10/11", 1);
map.set("10/12", 2);

function addNewItem(item, map) {
  map.forEach((value, key, map) => {
    map.set(key, value + 1);
  });
  map.set(item, 0);
  return map;
}

const newMap = addNewItem("10/9", map);

console.log(newMap);

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement