1

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,
}
7
  • How are you using this Map object? Commented Jan 21, 2021 at 5:35
  • I am storing indices of a list in this map, for getting a fast indexing. Commented Jan 21, 2021 at 5:36
  • 3
    Iterate over the keys of the map and set them one by one?... Commented Jan 21, 2021 at 5:42
  • 1
    You do realize your example is flawed, right? The Map maintains insertion order - so "10/9' will be the last key in the list, it cannot be the first in your given scenario. Commented Jan 21, 2021 at 5:45
  • 2
    [...map.keys()].forEach(k => map.set(k, map.get(k) +1)); and then map.set("10/9", 0); Commented Jan 21, 2021 at 5:45

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

You can place the item at any position here based on its value and increment the value greater then or equal to assigned value.

var map = new Map();

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



function logMapElements(value, key, map, set_key, set_value) {
    if (set_value <= value) {
      map.set(key, value+1);
    }
    
}

function setMapElement(set_key, set_value) {
        map.forEach((key, value, map) => logMapElements(key, value, map, set_key, set_value))
    map.set(set_key, set_value);
  

  
  
}

setMapElement("10/9", 0);
console.log(map.get("10/9"));
console.log(map.get("10/10"));

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.