You can calculate the median of an array of numbers in JavaScript in the following steps:
- Sort the array in ascending order;
- Determine the median, which would be one of the following:
- Element at the middle index if the array has an odd number of elements, or;
- Average of the two elements at the middle indexes if the array has an even number of elements.
For example, you can implement this in the following way:
function median(arr) {
// 1: sort array in ascending order
const sortedArr = arr.sort();
const middleIndex = arr.length / 2;
// 2.1: if odd, return middle element
if (arr.length % 2 !== 0) {
return arr[Math.floor(middleIndex)];
}
// 2.2: if even, return average of two middle elements
return (arr[middleIndex - 1] + arr[middleIndex]) / 2;
}
console.log(median([1, 2])); // 1.5
console.log(median([4, 1, 7])); // 4
console.log(median([3, 7, 5, 1, 8, 9])); // 6
console.log(median([39, 3, 14, 29, 23, 13, 23, 23, 40, 23, 21, 5, 7, 12, 56])); // 23
For arrays with an odd length, rounding down the middle index (i.e. Math.floor(middleIndex) is needed because dividing an odd array length by 2 would yield a fraction.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.