Learn Advanced Array Methods by Building a Statistics Calculator - Step 34

Tell us what’s happening:

Describe your issue in detail here.
Can someone please explain how the array.forEach() is working here.

counts[el] = (counts[el] || 0) + 1;

when I log counts, it has the numbers entered as values and the how many times the numbers have been repeated as the keys. And I have 0 idea on how thats happening with 1 single line of code here.

Your code so far

const getMode = (array) => {
  const counts = {};
  array.forEach((el) => {
    counts[el] = (counts[el] || 0) + 1;
  })
  if (new Set(Object.values(counts)).size === 1) {
    return null;
  }
  console.log(counts);
  const highest = Object.keys(counts).sort(
    (a, b) => counts[b] - counts[a]
  )[0];
  const mode = Object.keys(counts).filter(
    (el) => counts[el] === counts[highest]
  );
  return mode.join(", ");
}



### Challenge Information:
Learn Advanced Array Methods by Building a Statistics Calculator - Step 34
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/learn-advanced-array-methods-by-building-a-statistics-calculator/step-34

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

Hi!
This line is trying to set the value of the counts object where the key is the number “el”. If there isn’t already a key with that number, it assumes the value is zero. The second step adds 1 to either the value at that key, or zero. The third step assigns this new value to that key.

So in the parentheses, counts[el] could be undefined, and if so, the algorithm then assumes the value zero.

Assume array = [“2”,“2”,“3”] and counts ={}. Then the forEach runs:
counts[“2”] = (counts[“2”] || 0) + 1

What happens? It is setting the key “2” equal to something. This is perfectly fine code and how we often set a key value pair in an object. What is the “something”? The first thing we encounter is trying to retrieve the value from the key “2”, but it doesn’t exist yet! So it returns undefined. In which case the || takes over and the value becomes 0. Then we add 1. So counts = {“2”: 1}.
Next pass: counts[“2”] = (counts[“2”] || 0) + 1. Now the value at “2” is 1, so the || 0 is ignored, and add 1 for a value of 2. Counts = {“2”: 2}.
Final pass: counts[“3”] = (counts[“3”] || 0) +1. There is no key of “3”, so it is undefined so the || 0 takes over then we add 1. Counts = {“2”: 2, “3”:1}.

I hope this helps!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.