It is easy to calculate a median for an array with an odd number of elements. To do this, you need to correctly calculate the average element index. Let’s try to derive the formula:
// Array length 3, middle element index 1
[1, 2, 3]
// Array length 5, middle element index 2
[1, 2, 3, 4, 5]
// Array length 7, middle element index 3
[1, 2, 3, 4, 5, 6, 7]
Let’s subtract one from the array length, divide it by two, and we got the index.
Muffin can send data arrays of different lengths, so you’ll have to check the number of elements for parity and, depending on result, find the median. To check for parity, let’s use the operator we are already familiar with: %.
var usersByDay = [1, 2, 3, 4, 5];
The code has changed, click “Run” or turn autorun on.
At the end of the program, add a check for an odd number of elements in the array: usersByDay.length % 2 !== 0.
If the condition is met, add variable medianIndex with value (usersByDay.length - 1) / 2.
Log this variable in the console.
In the same condition branch, add variable median with value usersByDay[medianIndex].
Have you forgotten your password or lost access to your profile? Enter your email connected to your profile and we will send you a link to restore access.
Forgot to connect your email to the profile? Email us and we’ll help.