Tell us what’s happening:
this is, what i have to do:
Declare a median
variable. Using the ternary operator, check if the length of array
is even. If the length of array
is even, find the two middle numbers and calculate the mean of those numbers. If the length of array
is odd, find the middle number and assign it to the median
variable.
and this is hint i get:
If the array.length
is even, your median
variable should use the getMean
function to calculate the mean of the two middle numbers. Your first argument should be the value of sorted
at array.length / 2
, and the second at array.length / 2 - 1
.
i dont know where my mistake is
Your code so far
javascript
/* file: script.js */
const getMean = (array) => array.reduce((acc, el) => acc + el, 0) / array.length;
// User Editable Region
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[array.length / 2] ;
}
// 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);
document.querySelector("#mean").textContent = mean;
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
Challenge Information:
Learn Advanced Array Methods by Building a Statistics Calculator - Step 22