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

Tell us what’s happening:

What am I missing in my code? It looks right to me but I feel like I might have overlooked something

MY CODE:

const getMedian = (array) => {
const sorted = array.sort((a, b) => a - b);
const length = array.length;

const median = length % 2 === 0 ?
getMean([sorted[length / 2], sorted[length / 2 - 1]]) :
sorted[Math.floor(length / 2)];

return median;
};

Challenge Information:

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

Hi @JVFET

The instructions did not ask you to declare a length variable.
Although the code is correct, the tests are checking for specific code, so will fail the tests.

Happy coding

Ok. I fixed the problem and deleted the length variable, but it still says the same error:

“Your median variable should use a ternary operator to check if the array.length is even.”

Here is my updated code:

const getMedian = (array) => {
const sorted = array.sort((a, b) => a - b);
const medianIndex = Math.floor(sorted.length / 2);

const median = sorted.length % 2 === 0 ?
getMean([sorted[medianIndex], sorted[medianIndex - 1]]) :
sorted[medianIndex];

return median;
};

1 Like

The test uses a regex so you pretty much have to write it as expected (which is unreasonable). Even if your code was to produce the correct result it wouldn’t matter.

You can look at the tests or skip forward to the next step to see how they want you to write the code.

https://github.com/freeCodeCamp/freeCodeCamp/blob/main/curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-advanced-array-methods-by-building-a-statistics-calculator/635090f47eb6d9563a6fed05.md

Im not really understanding what the solution to this test is soI looked at the following step for the answer.

This is the required solution in this particular step:

Mod edit: solution code removed

@ritesh.poudel.34

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.