Calculate the Median value in JavaScript

The median represents the central value of a specific dataset or collection of information. It is crucial for determining the midpoint of the values within both even and odd arrays. In JavaScript, there are multiple methods available to calculate the median of an array.

The problem with the array of Median

When utilizing the array composed of odd-valued elements, we will select the central element to present it as the output. For instance, consider the array [1, 2, 3, 4, 5] stored in the database. In this case, the value 3 represents the median of this array.

Reasoning for the specified problem

  • We will write a method in the code to determine the Median of the array.
  • Additionally, the middle index of the array is determined by dividing its element length by two.
  • If the array has an odd number of elements, the index is the array's median index.
  • If the array contains an even number of the element set, then the index of the Median will be set to the left of the Median.
  • Next, we use the sort method to accept a comparison function as an input. The sort method sorts the values according to ascending order.
  • If the array's length is even, then the element returns the average of the two middle values.
  • The values at the centre of the index are added, and the total will then be divided by two.
  • We will return the middle value if the length of the array is odd.
  • Method 1:

The fundamental approach involves sorting the array and presenting the median as the middle value when the array contains an even number of elements. Conversely, in cases where the array has an odd count of elements, the median is determined by calculating the average of the two central values.

Algorithm of the median value in javascript

The following steps are used to get the Median of the array.

  • Initially, sort the array.
  • Next, determine if the array's element count is even or odd.
  • If the array length is odd, then return the array's mid value.
  • If the array length is even, the Median is the mean of the two middle numbers.
  • Examples

The subsequent examples illustrate the mean or median values derived from sorted and unsorted arrays, including both odd and even numbers, as well as the corresponding hash values.

Example 1:

The subsequent examples illustrate the median value derived from an even-sized array that is not sorted.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of unsorted and even value array </h4>
<p> . A middle value of a given set of data or information is called a median. </p>
<script>
//Function for calculating the median value
function findMeadianValue(a)
{
var concat_var = a;
concat_var = concat_var.sort(
function (a, b) { return a - b });

console.log(concat_var);
var length_var = concat_var.length;

if (length_var  % 2 == 1) {

// If length is odd
console.log(concat_var[(length_var / 2) - .5])
return concat_var[(length_var / 2) - .5]

}
else {
console.log((concat_var[length_var / 2]
+ concat_var[(length_var / 2) - 1]) / 2);

return (concat_var[length_var / 2]
+ concat_var[(length_var / 2) - 1]) / 2;
}
}
let a = [1, 25, 3, 51, 6, 7, 33, 44]
// Function call and get output
document.write("Median = " + findMeadianValue(a) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values by utilizing the Function.

Example 2:

The subsequent examples illustrate the median value of an array that is both odd in length and unsorted.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of unsorted and odd value array </h4>
<p> . A middle value of a given set of data or information is called a median. </p>
<script>
//Function for calculating the median value
function findMeadianValue(a)
{
var concat_var = a;
concat_var = concat_var.sort(
function (a, b) { return a - b });

console.log(concat_var);
var length_var = concat_var.length;

if (length_var  % 2 == 1) {

// If length is odd
console.log(concat_var[(length_var / 2) - .5])
return concat_var[(length_var / 2) - .5]

}
else {
console.log((concat_var[length_var / 2]
+ concat_var[(length_var / 2) - 1]) / 2);

return (concat_var[length_var / 2]
+ concat_var[(length_var / 2) - 1]) / 2;
}
}
let a = [1, 25, 3, 51, 6, 7, 44]
// Function call and get output
document.write("Median of the odd array length = " + findMeadianValue(a) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values calculated through the Function.

Example 3:

The subsequent illustrations demonstrate the median value derived from an array that is both sorted and contains an even number of elements.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of sorted and even value array </h4>
<p> A middle value of a given set of data or information is called a median. </p>
<script>
//Function for calculating the median value
function findMeadianValue(a)
{
// First, sort the  given array
const mid = Math.floor(a.length / 2);
const sortArr = a.sort((a1, b) => a1 - b);
// Check for even condition
if (a.length % 2 === 0) {
return (sortArr[mid - 1] + sortArr[mid]) / 2;
} else {
return sortArr[mid];
}
}
let a1 = [1, 3, 6, 17, 26, 37];
let a2 = [1, 3, 6, 17, 26, 37, 60];
// Function call and get output
document.write("Median for even array length = " + findMeadianValue(a1) + "<br>");
document.write("Median for odd array length = " + findMeadianValue(a2) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values by utilizing the Function.

Example 4:

The subsequent example illustrates how to determine the median of a multi-index array. We can organize the various sub-arrays in order, merge them into a single array, and then compute the median for that array.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of unsorted and odd value array </h4>
<p> . A middle value of a given set of data or information is called a median. </p>
<script>
//Function for calculating the median value
function findMeadianValue(arr, n) {
// Initializing an array
let var1 = [];
// Adding elements to the array
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[0].length; j++)
var1.push(arr[i][0]);
}
// Sorting the multi_index array
var1 = var1.sort(function(a, b){return a-b});
// Return middle element of the array
return var1[var1.length / 2];
}
// data in the array and its length
let a1 = [[1, 3], [4, 4], [5, 1], [6, 3]];
let a2 = [[1, 3], [4, 10], [7, 1], [6, 3], [7, 5],];
let num1 = a1.length;
let num2 = a2.length;
// Function call and get output
document.write("Median = " + findMeadianValue(a1, num1) + "<br>");
document.write("Median = " + findMeadianValue(a2, num2) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values utilizing the Function.

Method 2:

Initially, we define the variable middle, which holds the value representing the center of the array, taking into account whether the length is odd or even. Next, we proceed to sort the array while ensuring that we avoid any mutations. A mutation refers to the act of assigning a new name to an object or transferring it to another object that has experienced a change.

This method utilizes references for both object and array data types. When the array has an even number of elements, the two values can be located at the positions arr((arr.length)/2) and arr(((arr.length)/2) +1). To determine the Median, calculate the average of these two integer values.

Examples

The examples provided below illustrate the average or median values derived from sorted and unsorted arrays, as well as those containing odd and even numbers, alongside the corresponding hash values.

Example 1:

The subsequent example illustrates how to calculate the Median for an array that has an even number of elements.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of unsorted and even value array </h4>
<p> A middle value of a given set of data or information is called a median. </p>
<b> use arr((arr.length)/2) + arr(((arr.length)/2) +1) for odd array median </b>
<br>
<script>
//Function for calculating the median value
function findMeadianValue(a1)
{
const middle_var = (a1.length + 1) / 2;

// Avoid mutating when sorting
const sorted_var = [...a1].sort((a, b) => a - b);
const isEven_var = sorted_var.length % 2 === 0;

return isEven_var ? (sorted_var[middle_var - 1.5]
+ sorted_var[middle_var - 0.5]) / 2 :
sorted_var[middle_var - 1];
}
let a1 = [1, 25, 3, 51, 6, 9, 33, 44]
// Function call and get output
document.write("Median = " + findMeadianValue(a1) + "<br>");
</script>
</body>
</html>

Output

The displayed results indicate the median values calculated through the Function.

Example 2:

The example below illustrates the calculation of the median for an array with an odd number of elements.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of unsorted and even value array </h4>
<p> A middle value of a given set of data or information is called a median. </p>
<b> use arr((arr.length)/2) + arr(((arr.length)/2) +1) for the even array median and middle value for the odd array median </b>
<script>
//Function for calculating the median value
function findMeadianValue(a1)
{
const middle_var = (a1.length + 1) / 2;

// Avoid mutating when sorting
const sorted_var = [...a1].sort((a, b) => a - b);
const isEven_var = sorted_var.length % 2 === 0;

return isEven_var ? (sorted_var[middle_var - 1.5]
+ sorted_var[middle_var - 0.5]) / 2 :
sorted_var[middle_var - 1];
}
let a1 = [1, 25, 3, 51, 6, 9, 33, 44, 60]
// Function call and get output
document.write("Median = " + findMeadianValue(a1) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values generated by utilizing the Function.

Example 3:

The subsequent illustration demonstrates the calculation of the Median for a multi-index array.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculates the median value of unsorted and even value array </h4>
<p> A middle value of a given set of data or information is called a median. </p>
<b> use arr((arr.length)/2) + arr(((arr.length)/2) +1) for the even array median and middle value for the odd array median </b> <br>
<script>
//Function for calculating the median value
function findMeadianValue(a1)
{
const middle_var = (a1.length + 1) / 2;

// Avoid mutating when sorting
const sorted_var = [...a1].sort((a, b) => a - b);
const isEven_var = sorted_var.length % 2 === 0;

return isEven_var ? (sorted_var[middle_var - 1.5]
+ sorted_var[middle_var - 0.5]) / 2 :
sorted_var[middle_var - 1];
}
let a1 = [[1, 25], [3, 51], [6], [9, 33], [44, 60, 71, 32]];
let a2 = [[1, 25], [3, 51], [6, 7], [9, 33], [44, 60]];
// Function call and get output
document.write("Median for odd multi-index array = " + findMeadianValue(a1) + "<br>");
document.write("Median for even multi-index array = " + findMeadianValue(a2) + "<br>");
</script>
</body>
</HTML

Output

The result displays the median values utilizing the Function.

Method 3:

In this scenario, we utilize both array slicing techniques and the Math library. The process begins with sorting the array in ascending order. Following that, we assess whether the length of the array is odd or even. In the case of an even length, we compute the average of the two central elements. Conversely, if the length is odd, we directly return the middle element.

Examples

The subsequent illustrations demonstrate the average or median values for sorted and unsorted arrays, as well as for both odd and even arrays, along with their corresponding hash values.

Example 1:

The subsequent illustration demonstrates how to calculate the median for arrays with both odd and even lengths.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculate the median value of odd value array </h4>
<p> A middle value of a given set of data or information is called a median. </p>
<script>
//Function for calculating the median value
function findMeadianValue(a1)
{
// Sort the given array
a1.sort((a, b) => a - b);

const length_val = a1.length;
const middle = Math.floor(length_val / 2);

// Check if the array length is even or odd
if (length_val% 2 === 0) {
// If even, return the average of the middle two elements
return (a1[middle - 1] + a1[middle]) / 2;
} else {
// If odd, return the middle element
return a1[middle];
}
}
let a1 = [1, 25, 3, 51, 36, 99, 33, 44, 60];
// Function call and get output
document.write("Median of odd array length = " + findMeadianValue(a1) + "<br>");
let a2 = [25, 3, 51, 36, 99, 33, 44, 60];
document.write("Median of even array length = " + findMeadianValue(a2) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values by utilizing the Function.

Example 2:

The subsequent example illustrates how to compute the median using both odd and even multi-index arrays. It is possible to utilize a multi-index array that contains elements of varying sizes.

Example

<!DOCTYPE html>
<html>
<head>
<title> Calculate Median value in Javascript </title>
</head>
<body style = "background-color:beige;">
<h2> Calculate Median value in Javascript </h2>
<h4> javascript calculate the median value of multi-index array </h4>
<p> A middle value of a given set of data or information is called a median. </p>
<script>
//Function for calculating the median value
function findMeadianValue(a1)
{
// Sort the given array
a1.sort((a, b) => a - b);
const length_val = a1.length;
const middle = Math.floor(length_val / 2);
// Check if the array length is even or odd
if (length_val% 2 === 0) {
// If even, return the average of the middle two elements
return (a1[middle - 1] + a1[middle]) / 2;
} else {
// If odd, return the middle element
return a1[middle];
}
}
let a1 = [[1, 25, 3], [51, 36], [99, 33, 44, 60]];
let a2 = [[1, 25, 3], [51, 36], [99, 33, 44, 60], [21, 45]];
// Function call and get output
document.write("Median = " + findMeadianValue(a1) + "<br>");
document.write("Median = " + findMeadianValue(a2) + "<br>");
</script>
</body>
</html>

Output

The result displays the median values utilizing the Function.

Complexity

  • The Function takes O(n log n) to execute because we chose a rapid sort technique, and it takes O(n log n) time to sort the elements (where n is the array's size).
  • Additionally, the Function uses O(1) space because the result is only being stored as the array's middle element.
  • In summary

The implemented code simplifies the task of determining the median of an array efficiently. The designed function operates with a time complexity of O(n log n) to execute. However, in cases where the array is already sorted, the time complexity can be reduced to O(n) because of the linear characteristics of the procedure.

Input Required

This code uses input(). Please provide values below: