| Viewed 150 times

How to Calculate the Median in javaScript?


I need to create a function that takes an array of numbers and return its median

1 Answer
Mohammad Qandeel
Answered
24

Try this function

function median(arr) {
  arr = arr.sort((a, b) => a - b)
  var middleIndex = Math.floor(arr.length / 2);
  return arr.length%2==1 ? 
    arr[middleIndex] : (arr[middleIndex-1] + arr[middleIndex])/2
}

Example

median([4,2]) // 3

median([4]) // 4

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

 


Related Questions