In this shot, we’ll learn how to get the median of an array of numbers in JavaScript.
The median is the middle value of the given list of data when it is arranged in order.
Given an array of numbers, find the median.
To find the median of an array of numbers, we face two cases:
Input:
arr = [9,4,6,3,8]
Output:
6
6
, which is the median.Input:
arr = [7,4,6,9,3,8]
Output:
6
6.5
.You can easily find the median if the number of elements is odd, but if the count is even, then we need to take an average of the two middle elements.
Let’s first take a look at an odd length array.
//given odd number of elementslet arr = [3,4,5,7,8]//sort the arrayarr.sort((a, b) => a - b)//declare median variablelet median;//if else block to check for even or oddif(arr.length%2 != 0){//odd case//find middle indexlet middleIndex = Math.floor(arr.length/2)//find medianmedian = arr[middleIndex]}else{//even case//find middle indexlet middleIndex = Math.floor(arr.length/2)//find medianmedian = (arr[middleIndex] + arr[middleIndex - 1])/2}//print medianconsole.log(median)
Line 2: We have an array arr
of numbers.
Line 5: We use the sort()
method to sort the array. The method sorts the array in alphabetical order by default, so we pass a comparator to sort according to numbers.
Line 8: We declare a variable median
that is used to store the median of the given array.
Line 11: We check if the given array length is even
or odd
.
odd
, the program executes the code block from lines 12 to 18.even
, the program executes the code block from lines 20 to 26.In the case of an odd length array, find the middle index and the median, which is the element present at the index in the array.
Now, let’s look at an even length array.
//given even number of elementslet arr = [7,4,6,9,3,8]//sort the arrayarr.sort((a, b) => a - b)//declare median variablelet median;//if else block to check for even or oddif(arr.length%2 != 0){//odd case//find middle indexlet middleIndex = Math.floor(arr.length/2)//find medianmedian = arr[middleIndex]}else{//even case//find middle indexlet middleIndex = Math.floor(arr.length/2)//find medianmedian = (arr[middleIndex] + arr[middleIndex - 1])/2}//print medianconsole.log(median)
Free Resources