Calculating median of an array in JavaScript

In this problem statement, our task is to calculate the median of an array with the help of Javascript functionalities. There are several ways that can be used to solve this task. One simple method to calculate median is using the built-in function of Javascript.

Understanding the Problem

The problem statement is to write a function in Javascript that will help to calculate the median of a given array. The median is the middle value when numbers are arranged in ascending order.

For example:

  • Array [1, 2, 3, 4, 5] has median 3 (middle element)
  • Array [1, 2, 3, 4] has median 2.5 (average of 2 and 3)

Algorithm

Step 1 ? Declare a function called median which takes an array parameter.

Step 2 ? Sort the array in ascending order using the sort() method.

Step 3 ? Calculate the middle index by dividing array length by 2.

Step 4 ? If array length is even, return average of two middle elements.

Step 5 ? If array length is odd, return the middle element.

Example

// Function to find the median of the given array
function median(arr) {
    const mid = Math.floor(arr.length / 2);
    const sortedArr = arr.sort((a, b) => a - b);
    
    if (arr.length % 2 === 0) {
        return (sortedArr[mid - 1] + sortedArr[mid]) / 2;
    } else {
        return sortedArr[mid];
    }
}

// Test with odd length array
const oddArray = [11, 12, 13, 14, 15, 16, 17, 18, 19];
console.log("Odd array median:", median(oddArray));

// Test with even length array
const evenArray = [5, 1, 4, 2];
console.log("Even array median:", median(evenArray));

// Test with unsorted array
const unsortedArray = [7, 3, 9, 1, 5];
console.log("Unsorted array median:", median(unsortedArray));
Odd array median: 15
Even array median: 2.5
Unsorted array median: 5

How It Works

The function first sorts the input array in ascending order. Then it calculates the middle index. For even-length arrays, it returns the average of the two middle elements. For odd-length arrays, it returns the single middle element.

Odd Length Array: [1, 3, 5, 7, 9] 1 3 5 7 9 Median = 5 Even Length Array: [2, 4, 6, 8] 2 4 6 8 Median = (4 + 6) / 2 = 5

Complexity Analysis

Time Complexity: O(n log n) due to the sorting operation, where n is the array size.

Space Complexity: O(1) as we only store a few variables regardless of input size.

Conclusion

This solution provides an efficient way to calculate the median by sorting the array and finding the middle value(s). The sorting step dominates the time complexity at O(n log n).

Updated on: 2026-03-15T23:18:59+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements