Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Map() increment value

I have a map as follows:

let map = new Map(); map.set("a", 1); //Map is now {'a' => 1} 

I want to change the value of a to 2, or increment it: map.get("a")++;

Currently, I am using the following:

map.set("a", (map.get("a"))+1); 

However, this does not feel right. Does anyone know a cleaner way of doing this? Is it possible?

like image 499
EDJ Avatar asked Dec 02 '18 20:12

EDJ


People also ask

How do you find entries on a map?

The Map. entries() method does not require any argument to be passed and returns an iterator object of the map. Applications: Whenever we want to get all the [key, value] pairs of each element of a map using an iterator object, we use the Map. entries() method.

How do you increment the value of an object?

To increment a value in an object, assign the value of the key to the current value + 1, e.g. obj. num = obj. num +1 || 1 . If the property exists on the object, its value gets incremented by 1 , and if it doesn't - it gets initialized to 1 .

How do you increment an item in an array?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

How do you increment in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.


1 Answers

The way you do it is fine. That is how you need to do it if you are working with primitive values. If you want to avoid the call to map.set, then you must revert to a reference to a value. In other words, then you need to store an object, not a primitive:

let map = new Map(); map.set("a", {val: 1}); 

And then incrementing becomes:

map.get("a").val++; 
like image 129
trincot Avatar answered Oct 09 '22 22:10

trincot