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,
}
Muhammad Faizan Uddin
  • 1,339
  • 12
  • 29
Conchi Bermejo
  • 283
  • 2
  • 14
  • How are you using this `Map` object? – adiga Jan 21 '21 at 05:35
  • I am storing indices of a list in this map, for getting a fast indexing. – Conchi Bermejo Jan 21 '21 at 05:36
  • 3
    Iterate over the keys of the map and set them one by one?... – user202729 Jan 21 '21 at 05: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. – Randy Casburn Jan 21 '21 at 05:45
  • 2
    `[...map.keys()].forEach(k => map.set(k, map.get(k) +1));` and then `map.set("10/9", 0);` – D. Seah Jan 21 '21 at 05:45
  • What you really want to do is store the dates in a `TreeSet` and use `.subset(...).size()` to determine the rank of items on demand. You'll need to provide a custom comparator, since `"10/9"` comes *after* `"10/10"` in a string sort. Or use a different type like `LocalDate` – Matt Timmermans Jan 21 '21 at 13:59
  • related: https://stackoverflow.com/questions/53584369/javascript-map-increment-value – Bergi Jan 05 '22 at 22:03

2 Answers2

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

Taghi Khavari
  • 6,272
  • 3
  • 15
  • 32
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"));
sourav satyam
  • 980
  • 5
  • 11