54

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
4

7 Answers 7

150
dict[key] = (dict[key] || 0) + 1;
Sign up to request clarification or add additional context in comments.

1 Comment

Great! One less lookup compared to dict[key] = dict[key] ? dict[key]+1 : 1
26

@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

1 Comment

very concise, exactly what I was looking for
4

Your pseudo-code is almost identical to the actual code:

if (key in object) {
    object[key]++;
} else {
    object[key] = 1;
}

Although I usually write:

if (!(key in object)) {
    object[key] = 0;
}

object[key]++;

Comments

3

You can use the ternary operator (?:) like this:

dictionary[key] ? 
    dictionary[key].value += 1 : 
    dictionary[key] = {value: 1};

Comments

1

You should check if the object has an own property with the new_item name first. If it doesn't, add it and set the value to 1. Otherwise, increment the value:

var dict = {};
var new_item = "Bill"

dict[new_item] = dict.hasOwnProperty(new_item)? ++dict[new_item] : 1;

The above is a bit wasteful as if the property exists, it increments it, then assigns the new value to itself. A longer but possibly more efficient alternative is if the property doesn't exist, add it with a value of zero, then increment it:

if (!dict.hasOwnProperty(new_item)) {
  dict[new_item] = 0;
}
++dict[new_item];

Comments

0

You can do this in a lot of ways. In general if you want to know if an Object has a key you use the in modifier with the key name. This looks like:

var key = "key name";
var dict = {};
var hasKey = (key in dict);

Though you can check if a value is set by simply testing if it is undefined. This being that in JavaScript if you don't have a value initialized and send it through an if statement it will act as a false. Which looks like:

var dict = {};
if(dict[key]) {
   print("key: " + dict[key]);
} else {
   print("Missing key");
}

Comments

0

If value exist then (prev value + 1) OR set initial value 1.

const obj = {};

addToObj = key =>{
// Using ternary operator
obj[key] = obj[key] ? (obj[key] + 1) : 1;
}

addToObj('alex');
addToObj('adam');
addToObj('maria');
addToObj('maria');
addToObj('alex');
addToObj('john');
addToObj('jack');
addToObj('rock');
console.log(obj);

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.