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

Tell us what’s happening:

So I have finished this project. I ran it with the array of [1, 4, 6, 9].
I found bugs in mine -

  1. The median showed up 5 - there is no 5 in the array. I’m no statistics major for sure, so 5 is the “center” of the array, but not the middle number.
  2. The variance showed up 8.5 (but the value should be 5, how far values are from mean, on average. The farthest is 4 : 9-5 and 5-1)

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

  const mean = getMean(numbers);
  const median = getMedian(numbers);
  const mode = getMode(numbers);
  const range = getRange(numbers);
  const variance = getVariance(numbers);


  document.querySelector("#mean").textContent = mean;
  document.querySelector("#median").textContent = median;
  document.querySelector("#mode").textContent = mode;
  document.querySelector("#range").textContent = range;
  document.querySelector("#variance").textContent = variance;


// User Editable Region

Your browser information:

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

Challenge Information:

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

the code is the code.
So for median, the code is:

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

What does this code do? (it took your array of [1,4,6,9] and took the 2 middle numbers 4, and 6 and found their average which is 5.

How about the code for variance? What does it do.
(the code isn’t magic, it just does whatever we told it to do)

if there is an even number of digits, the median is calculated taking the two middle numbers and averaging them. If there is an odd number of digits, it’s the middle number. It works fine!

the variance of X is equal to the mean of the square of X minus the square of the mean of X.

So calculating (1^2 + 4^2 + 6^2 + 9^2) / 4 - ((1+4+6+9)/4)^2