Calculating median of an array JavaScript



We are required to write a JavaScript function that takes in an array of Numbers and returns its median.

Statistical Meaning of Median

The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average.

Approach

First, we will sort the array, if its size is even, we will need extra logic to deal with two middle numbers.

In these cases, we will need to return the average of those two numbers.

Example

const arr = [4, 6, 2, 45, 2, 78, 5, 89, 34, 6];
const findMedian = (arr = []) => {
   const sorted = arr.slice().sort((a, b) => {
      return a - b;
   });
   if(sorted.length % 2 === 0){
      const first = sorted[sorted.length / 2 - 1];
      const second = sorted[sorted.length / 2];
      return (first + second) / 2;
   }
   else{
      const mid = Math.floor(sorted.length / 2);
      return sorted[mid];
   };
};
console.log(findMedian(arr));

Output

And the output in the console will be −

6

Advertisements