Calculate the Median of an Array in JavaScript

Aug 24, 2022

To calculate the median of an array in JavaScript, perform the following steps:

  1. Make sure there are elements in the array.

  2. Sort the array.

  3. find the midpoint of the array by dividing the length of the array by 2.

  4. Calculate the median:

median([2, 1, 3, 4]);

function median(arr) {
  if (arr.length == 0) {
    return; // 0.
  }
  arr.sort((a, b) => a - b); // 1.
  const midpoint = Math.floor(arr.length / 2); // 2.
  const median = arr.length % 2 === 1 ?
    arr[midpoint] : // 3.1. If odd length, just take midpoint
    (arr[midpoint - 1] + arr[midpoint]) / 2; // 3.2. If even length, take median of midpoints
  return median;
}

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials