w3resource

JavaScript: Get the median of an array of numbers

JavaScript fundamental (ES6 Syntax): Exercise-88 with Solution

Write a JavaScript program to get the median of an array of numbers.

Note: Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

  • Find the middle of the array, use Array.prototype.sort() to sort the values.
  • Return the number at the midpoint if Array.prototype.length is odd, otherwise the average of the two middle numbers.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2
// Define the function 'median' to find the median value of an array.
const median = arr => {
  const mid = Math.floor(arr.length / 2),
    nums = [...arr].sort((a, b) => a - b);
  return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};

// Example usage:
console.log(median([5, 6, 50, 1, -5])); // Outputs: 5 (median of the array)
console.log(median([1, 2, 3, 4, 5])); // Outputs: 3 (median of the array)

Output:

5
3

Visual Presentation:

JavaScript Fundamental: Get the median of an array of numbers

Flowchart:

flowchart: Get the median of an array of numbers

Live Demo:

See the Pen javascript-basic-exercise-88-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to get the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).
Next: Write a JavaScript program to negates a predicate function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-88.php