In this shot, we will 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
, and that 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 elements let arr = [9,4,6,3,8] //sort the array arr.sort((a, b) => a - b) //declare median variable let median; //if else block to check for even or odd if(arr.length%2 != 0){ //odd case //find middle index let middleIndex = Math.floor(arr.length/2) //find median median = arr[middleIndex] }else{ //even case //find middle index let middleIndex = Math.floor(arr.length/2) //find median median = arr[middleIndex] + arr[middleIndex + 1] } //print median console.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 elements let arr = [7,4,6,9,3,8] //sort the array arr.sort((a, b) => a - b) //declare median variable let median; //if else block to check for even or odd if(arr.length%2 != 0){ //odd case //find middle index let middleIndex = Math.floor(arr.length/2) //find median median = arr[middleIndex] }else{ //even case //find middle index let middleIndex = Math.floor(arr.length/2) //find median median = (arr[middleIndex] + arr[middleIndex - 1])/2 } //print median console.log(median)
RELATED TAGS
CONTRIBUTOR
View all Courses