
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Calculating median of an array JavaScript
We are required to write a JavaScript function that takes in an array of Numbers and returns its median.
Statistical Meaning of Median
The median is the middle number in a sorted, ascending or descending, list of numbers and can be more descriptive of that data set than the average.
Approach
First, we will sort the array, if its size is even, we will need extra logic to deal with two middle numbers.
In these cases, we will need to return the average of those two numbers.
Example
const arr = [4, 6, 2, 45, 2, 78, 5, 89, 34, 6]; const findMedian = (arr = []) => { const sorted = arr.slice().sort((a, b) => { return a - b; }); if(sorted.length % 2 === 0){ const first = sorted[sorted.length / 2 - 1]; const second = sorted[sorted.length / 2]; return (first + second) / 2; } else{ const mid = Math.floor(sorted.length / 2); return sorted[mid]; }; }; console.log(findMedian(arr));
Output
And the output in the console will be −
6
- Related Articles
- Calculating median of an array in JavaScript
- Calculating average of an array in JavaScript
- Calculating variance for an array of numbers in JavaScript
- Finding median index of array in JavaScript
- Calculating the median of all pixels for each band in an image using the Pillow library
- Maximize the median of an array in C++
- Swift Program to Find Median of an Unsorted Array
- Calculating resistance of n devices - JavaScript
- Find Mean and Median of an unsorted Array in Java
- Calculating excluded average - JavaScript
- Median of two sorted array
- Calculating least common of a range JavaScript
- Program for Mean and median of an unsorted array in C++
- Program to Find Out Median of an Integer Array in C++
- Calculating the sum of digits of factorial JavaScript

Advertisements