Calculating median of an array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for calculating median of an array in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Calculating median of an array</h1>
<div><pre class="sample"></pre></div>
<div class="result"></div>
<button class="Btn">Calculate</button>
<h3>Click on the above button to calculate the median of the above array</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 5, 6, 99, 12, 11, 22];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      let middle = Math.floor(arr.length / 2);
      arr = [...arr].sort((a, b) => a - b);
      if (arr.length % 2 !== 0) {
         resEle.innerHTML = "Median = " + arr[middle];
      } else {
         resEle.innerHTML = "Median = " + (arr[middle - 1] + arr[middle]) / 2;
      }
   });
</script>
</body>
</html>

Output

On clicking the ‘Calculate’ button −

raja
Published on 17-Jul-2020 07:50:43
Advertisements