How might I add check to see if a key already exists, and if does, increment the value, and if it doesn't exist, then set the initial value?
Something like this pseudo-code:
var dict = {}; var new_item = "Bill" If new_item not in dict: dict[new_item] = 1 else: dict[new_item] += 1
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 .
Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.
To change the value of an object in an array:Use the Array. map() method to iterate over the array. Check if each object is the one to be updated. Use the spread syntax to update the value of the matching object.
dict[key] = (dict[key] || 0) + 1;
@snak's way is pretty clean and the ||
operator makes it obvious in terms of readability, so that's good.
For completeness and trivia there's this bitwise way that's pretty slick too:
dict[key] = ~~dict[key] + 1;
This works because ~~
will turn many non-number things into 0
after coercing to Number. I know that's not a very complete explanation, but here are the outputs you can expect for some different scenarios:
~~(null) 0 ~~(undefined) 0 ~~(7) 7 ~~({}) 0 ~~("15") 15
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With