I am practicing counting the frequency of unique elements in an array using this function, which I found here on StackOverflow:
let numArray = [1,3,8,10,39,67,88,12,11,9,1,8,1,8]
let countFrequency = function(arr){
var counts = {};
for (var i = 0; i < arr.length; i++) {
var num = arr[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
}
console.log(counts)
}
and then calling the function like so:
countFrequency(numArray);
And the result is this: {"1":3, "3":1, "8":3,...etc} which is correct and the desired behaviour.
However. I have no idea why this works and what is happening 'under the hood'. This is a common solution here on StackOverflow for this type of problem, but I can't find a clear explanation of this line:
counts[num] = counts[num] ? counts[num] + 1 : 1;
I know this is a ternary operator and how the operator itself works, but cannot for the life of me understand how it is building the 'counts' object. Could anyone please explain exactly how this solution works, or point me in the direction of an article that explains this? I think this would be useful for others who are learning this technique too, so thanks in advance!