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

Tell us what’s happening:

Hi everyone, so, i have this code that i need to change to a ternary operator:

const getMode = (array) => {
  const counts = {};
  array.forEach(el => {
    if (counts[el]) {
      counts[el] += 1;
    } else {
      counts[el] = 1;
    }
  });
  return counts;
}

I did it in two different ways, both showing errors:

array.forEach(el => counts [el] ? counts [el] += 1  :  counts[el] = 1;

the other:


array.forEach(el => (counts[el] = counts[el] || 0) + 1);

I tnk i understood what is asked but im stuck lol.

Your code so far

/* file: script.js */
const getMean = (array) => array.reduce((acc, el) => acc + el, 0) / array.length;

const getMedian = (array) => {
  const sorted = array.sort((a, b) => a - b);
  const median =
    array.length % 2 === 0
      ? getMean([sorted[array.length / 2], sorted[array.length / 2 - 1]])
      : sorted[Math.floor(array.length / 2)];
  return median;
}


// User Editable Region

const getMode = (array) => {
  const counts = {};
  array.forEach(el => counts[el] = (counts[el] || 0) + 1
  });
  return counts;
}

// User Editable Region


const calculate = () => {
  const value = document.querySelector("#numbers").value;
  const array = value.split(/,\s*/g);
  const numbers = array.map(el => Number(el)).filter(el => !isNaN(el));
  
  const mean = getMean(numbers);
  const median = getMedian(numbers);
  console.log(getMode(numbers));

  document.querySelector("#mean").textContent = mean;
  document.querySelector("#median").textContent = median;
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36

Challenge Information:

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

Hi there, welcome to the community! :blush:

You’re on the right track, but there’s a small issue with your forEach callback.

The lesson specifically asks you to:

  • Use a ternary operator instead of if...else
  • Convert the forEach callback to an expression body (no {})

Right now, your code does use an expression body, but the way you update counts[el] isn’t following the ternary format the lesson expects.

Try adjusting your code so that instead of (counts[el] || 0) + 1, you explicitly check if counts[el] exists and update it accordingly using a ternary.

Give it a shot, and let me know if you need a hint! Happy coding!

wow, this one wass tough for me. I will redo it more times, so i can understand deeper what i did. I got out from this with the feeling that, if i had to do this again a month from now, i wouldnt be able lol. Thanks for your time!

btw, my major flaw was that i wasnt following what was asked and wasnt assigning a variable name.

1 Like