Skip to content

median

Calculates the median (middle value) of an array of numbers. For an even-length array, returns the average of the two middle values. Returns NaN for an empty array. Does not mutate the input array.

The median is the 50th percentile — this delegates to it rather than duplicating its sort/interpolation logic.

Available since v3.0.3

import { median } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { median } from 'helpers4/array';
median(array: readonly number[]): number
ParameterTypeDescription
arrayreadonly number[]The array of numbers

number — The median value, or NaN if the array is empty

Returns the middle value once sorted.

median([3, 1, 2])
// => 2

Averages the two middle values.

median([1, 2, 3, 4])
// => 2.5

View source on GitHub