To calculate median with JavaScript, we can sort the numbers and get the middle value.
For instance, we write
const median = (numbers) => {
const sorted = Array.from(numbers).sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 0) {
return (sorted[middle - 1] + sorted[middle]) / 2;
}
return sorted[middle];
};
console.log(median([4, 5, 7, 1, 33]));
to define the median
function.
In it, we call sort
on the copied numbers
array after copying it with Array.from
to sort the numbers in ascending order.
Then we check if the length of the sorted
array is event.
We get the middle
index by taking the floor of the length divided by 2.
If it is, then we take the average of the 2 middle numbers.
Otherwise, we return the middle number.