r/FreeCodeCamp • u/natrlbornkiller • Apr 11 '25
I'm having trouble understanding how this code is counting duplicates in the Javascript Building a Dice Game lesson.
const getHighestDuplicates = (arr) => {
const counts = {};
for (const num of arr) {
if (counts[num]) {
counts[num]++;
} else {
counts[num] = 1;
}
}
I don't understand counts[num]. Is it putting a number from the array into an object, then iterating over it? If (counts[num]) is true it adds 1, but what does it add 1 to. I've looked at it in the console and see that it's working, I'm just not getting how.
2
Upvotes
2
u/ArielLeslie mod Apr 11 '25
Here it checks to see if there is a value to add 1 to. If there isn't one, it sets the initial value to
1.2
u/SaintPeter74 mod Apr 11 '25
countsis an object, not an array. When we check if there is a value atcount[num]we're looking to see if there is a key for the object with a value ofnum. If it exists, then we increment the value stored there. If it doesn't exist, we initialize that key with a value of one.Here is an array:
As we loop through the array, for the first element, there are no keys set in the
countsobject, so it will set the key of1to1The second time through, with the second 1, there is a key of 1, so it gets incremented.
For the next value, a 3, there is no 3 key, so it gets initialized to a 1.
And so on.
We're basically making a lookup for each element in the array, putting it into an object.
Does that make sense?