medianBy
Calculates the median of an array based on a selector function.
1/**
2 * Calculates the median of an array based on a selector function.
3 *
4 * @param arr - Array of items.
5 * @param fn - Function that returns a numeric value from each item.
6 * @returns The median value, or undefined if array is empty.
7 */
8export function medianBy<T>(arr: T[], fn: (item: T) => number): number | undefined {
9 if (arr.length === 0) return undefined;
10
11 const values = arr.map(fn).sort((a, b) => a - b);
12 const mid = Math.floor(values.length / 2);
13
14 return values.length % 2 === 0
15 ? (values[mid - 1] + values[mid]) / 2
16 : values[mid];
17}
Custom Selector Support
Works with complex data structures by allowing a selector function to extract numeric values.
Type-Safe with Generics
Leverages TypeScript generics to ensure flexibility without sacrificing type safety.
Handles Both Even and Odd Lengths
Correctly computes the median for datasets of any size, using proper averaging when needed.
Pure and Predictable
No side effects; consistently returns the same output for the same input, aiding testability.
Graceful Handling of Empty Input
Returns
undefined
instead of throwing an error, enabling safe integration into larger flows.
Tests | Examples
1test('medianBy - odd count', () => {
2 const data = [{ n: 5 }, { n: 1 }, { n: 3 }];
3 expect(medianBy(data, x => x.n)).toBe(3);
4});
5
6test('medianBy - even count', () => {
7 const data = [{ n: 1 }, { n: 2 }, { n: 4 }, { n: 6 }];
8 expect(medianBy(data, x => x.n)).toBe(3);
9});
10
11test('medianBy - all same values', () => {
12 const data = [{ v: 2 }, { v: 2 }, { v: 2 }];
13 expect(medianBy(data, x => x.v)).toBe(2);
14});
15
16test('medianBy - empty array', () => {
17 expect(medianBy([], x => 1)).toBeUndefined();
18});
Common Use Cases
Statistical Analysis
Calculate medians from datasets such as survey responses, benchmark results, or sensor readings.
Financial Tools
Determine the median value of incomes, prices, or investment returns from structured data.
Outlier Detection
Use the median to establish central tendency for further comparison or filtering.
UI Summaries
Display median values in dashboards or reports to provide context beyond averages.
Education & Grading Systems
Compute the median score in a set of test results or assignments for fairness evaluation.