On the Udemy Javascript course, there was a challenge, which was about creating an object
with key-value
pair from the array
and finding the number of occurrences
of each key. Thus, the key
is the array element
, and the value
of each key is the number of occurrences
of that key.
However, the solution to the challenge was the following two methods.
const sequential = ["first", "second", "third", "forth", "first", "first"];
const sequentialObject1 = {};
const sequentialObject2 = {};
for (const seq of sequential) {
// Method One:
sequentialObject1[seq] ? sequentialObject1[seq]++ : (sequentialObject1[seq] = 1);
// Method Two:
sequentialObject2[seq]++ || (sequentialObject2[seq] = 1);
}
console.log(sequentialObject1);
console.log(sequentialObject2);
The thing that I couldn't understand is, how the provided solution could find the number of occurrences
when there is no comparison process
to compare and find the occurrences. The solution seems to me like has nothing to do with finding the number of occurrences, but in fact, it can find them.
I understand what the increment operator
does, but don't understand the comparison process
, or how it happens!
So, could you please make me understand what is happening behind the scenes?
Thanks for your help.