Median of an array of numbers in JavaScript

Last Updated : 22 Jan, 2026

The median is the middle value of a sorted numeric array. If the array length is even, the median is the average of the two middle values.

  • Sort the array in ascending order.
  • If the array length is odd, pick the middle element.
  • If the array length is even, average the two middle elements.
  • Used in statistics to represent the central tendency of data.
JavaScript
function median(arr) {
    var sorted = arr.sort(function (a, b) {
        return a - b;
    });

    var length = sorted.length;

    if (length % 2 === 1) {
        return sorted[(length / 2) - 0.5];
    } else {
        return (sorted[length / 2] + sorted[(length / 2) - 1]) / 2;
    }
}

var arr = [1, 4, 7, 9];
console.log(median(arr));

Output
5.5

[Approach 1]: This approach calculates the median by first identifying the middle index, sorting the array without mutating the original data, and then handling even and odd length cases accordingly.

  • Calculate a common middle index.
  • Sort the array without mutation.
  • Return the middle element (odd) or the average of two middle elements (even).
JavaScript
function median(arr) {
    const middle = (arr.length + 1) / 2;

    // Avoid mutating when sorting
    const sorted = [...arr].sort((a, b) => a - b);
    const isEven = sorted.length % 2 === 0;

    return isEven
        ? (sorted[middle - 1.5] + sorted[middle - 0.5]) / 2
        : sorted[middle - 1];
}

var arr = [1, 4, 7, 9];
console.log(median(arr));

Output
5.5

[Approach 2]: This method finds the median by sorting the array and handling even and odd lengths differently.

  • Sort the array in ascending order using array slicing to avoid mutation.
  • Return the middle element for odd lengths or the average of the two middle elements for even lengths.
JavaScript
function median(arr) {
    
    // Sort the array
    arr.sort((a, b) => a - b);

    const length = arr.length;
    const middle = Math.floor(length / 2);

    // Check if the array length is even or odd
    if (length % 2 === 0) {
       
        // If even, return the average of middle two elements
        return (arr[middle - 1] + arr[middle]) / 2;
    } else {
        
        // If odd, return the middle element
        return arr[middle];
    }
}

const arr1 = [1, 4, 7, 9];
console.log(median(arr1)); 

const arr2 = [5, 3, 1, 8, 90];
console.log(median(arr2)); 

Output
5.5
5
Comment