Learn Functional Programming by Building a Spreadsheet - Step 25

Tell us what’s happening:

I dont understand this challenge step when it says: The first element of the array passed to

average()

should be the element at the

middle

index of your

sorted

array. The first element of the array passed to

average()

should be the element at the

middle + 1

index of your

sorted

array. If the ternary is false, you should return the value of

sorted

at the

middle

index. Use

Math.ceil()

to round the

middle

value up.

Your code so far

 return isEven(length) ? average([sorted[middle + 1] + sorted[middle]]) : Math.ceil(sorted[middle]);
}

Your browser information:

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

Challenge Information:

Learn Functional Programming by Building a Spreadsheet - Step 25

Hi there. Can you reformat your post so it’s easier to read please?

 return isEven(length) ? average([sorted[middle] + sorted[middle + 1]]) : Math.ceil(sorted[middle]);

i have this code snippet. when i try to enter the code, it doesnt go through. on the console it says the first element passed to average() should be at the middle + 1 index of sorted array. but then it also says the first element passed to average() should be at the middle index of the sorted array…
So i wanted to know which is it supposed to be, cause im a little confused now.

1 Like

Okay. Let’s figure this out left to right. The average function takes an array of numbers and returns the average. They sum the numbers up and divide by the length for you.

const average = nums => sum(nums) / nums.length;

So all you have to is pass in both numbers into a single array.

Going further right, I see you’re trying to take round the number in the sorted array at the index of middle. I don’t think that’s quite what the instructions are after. The middle index is calculated over here.

const middle = length / 2 - 1;

Sometimes when you divide, you get decimals. Arrays don’t know what decimals are, so you need to round that index up to the nearest whole number.

I hope this helps. Let me know if you need any further clarification.

1 Like

So what exactly is my mistake in the code snippet i provided?

There’s two mistakes in your code.

average([sorted[middle + 1] + sorted[middle]])

This code adds together the numbers at sorted[middle] and sorted[middle + 1].

Your second mistake is in this piece of code.

Math.ceil(sorted[middle]);

If given an array like the following, [1,2,3,4,5] , your code will produce a NaN error because the middle will be 1.5 instead of 2.

2 Likes

the test requires me to use Math.ceil()

Yes. You have to round the middle index up with Math.ceil.

1 Like

Thank you so much for your help

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