# How to get median of an array of numbers in JavaScript ?

• Last Updated : 22 Apr, 2021

In this article, we will see how to find the median of an array using JavaScript.

Examples:

```Input arr1 : [1 4 7 9]
Output : 5.5
Explanation : The median of the two sorted array is
the middle elements which is 5 if the
arrayLength =arr1.length + arr2.length is odd
if the array length is even then it will be
the average of two number

Input: arr1 : [5 3 1 8 90]

Output: 5
Explanation : The median is average of two number
because the array.length is even for this case.```

Approach: Here we first sort the array and then will find the array length. If the array length is even then median will be arr[(arr.length)/2] +arr[((arr.length)/2)+1]. If the array length is odd then the median will be a middle element.

## Javascript

 ` `

Output:

`5.5`

Time Complexity:

`O(n + m)`

Approach 2: Here we have first made the variable middle which has the middle value irrespective of length whether array length will be odd and even. Now after that we sort the array by avoiding mutation. Mutation means changing the object name with another object name or passing the object to another object called mutation.

It can be done with reference data types which are arrays, Object So For now avoid this. After that if the length of array is even then we have the two value in array at pos arr((arr.length)/2) + arr(((arr.length)/2) +1). Then take the mean of these two number and return as a median.

## Javascript

 ` `

Output:

`5.5`

Time Complexity:

`O(n+m)`

My Personal Notes arrow_drop_up
Recommended Articles
Page :