Search code examples
javascriptarraysobjectkey-value

Finding number of occurrences with key-value pair object in javascript


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.


Solution

  • The trick here is using the object sequentialObject. It is a dictionary which keeps track of value in sequential. When the first occurrence of value is found inside the for loop it is added to the sequentialObject with count 1 and every time the value is found again the value is incremented, once all the items are done it gives the dictionary of values and their count.

    sequentialObject[seq] ? sequentialObject[seq]++ : (sequentialObject[seq] = 1) translates to: if seq exists in sequentialObject then increment its value else set its value to 1.