How to calculate the median of an array by JavaScript
This article mainly explains "JavaScript how to find the median of an array". The explanation in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian and go deep into it slowly to study and learn "JavaScript how to find the median of an array" together.
Methods: 1. Sort the array and find the array length;2. Determine whether the array length is even or odd. If it is even, the median is "(array name [(array length)/2]+ array name [(array length)/2)+1])/2". If it is odd, the median is "array name [(array length/2)-0.5]".
Operating environment of this tutorial: Windows 7 system, Javascript version 1.8.5, Dell G3 computer.
A median is the number in the middle of an ordered set of data, representing a value in a sample, population, or probability distribution that divides the set of values into equal upper and lower parts. For a finite number set, you can find the median by ranking all observations high and low. If there are an even number of observations, the median is usually taken as the average of the two values in the middle.
JavaScript How to find the median of an array
Realization of ideas:
Sort the array and find the array length
If the array length is even, then the median will be arr[(arr.length)/2] +arr[(arr.length)/2)+1]/ 2.
If the array length is odd, the median will be the middle element.
Implementation code:
function medianof2Arr(arr1) { var concat = arr1; concat = concat.sort( function(a, b) { return a - b }); console.log(concat); var length = concat.length; if (length % 2 == 1) { //if the length is odd console.log("Median is: "+(concat[(length / 2)-0.5])) } else { //if the length is even console.log("Median is: "+(concat[length / 2]+concat[(length / 2) - 1]) / 2); }}arr1 = [1, 4, 7, 9,2]medianof2Arr(arr1);
arr1 = [1, 4, 7, 9]medianof2Arr(arr1);
Thank you for reading, the above is the content of "JavaScript how to find the array median", after the study of this article, I believe that everyone has a deeper understanding of JavaScript how to find the array median, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!