Home >Web Front-end >JS Tutorial >How to find the median of an array in JavaScript
Method: 1. Sort the array and find the array length; 2. Determine whether the array length is an even number or an odd number. If it is an even number, the median is "(array name[(array length)/ 2] Array name [((array length)/2) 1])/2", if it is an odd number, the median is "array name [(array length/2)-0.5]".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
The median is the middle number in a set of data arranged in order, representing a value in a sample, population or probability distribution, which can divide the value set into two equal upper and lower parts. For a finite set of numbers, you can sort all the observed values and find the middle one as the median. If there is an even number of observations, the average of the two middle values is usually taken as the median.
How to find the median of an array in JavaScript
Implementation idea:
Yes Sort the array and then find the length of the array
If the length of the array is an even number, 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) { // 如果长度是奇数 console.log("中位数为: "+(concat[(length / 2) - 0.5])) } else { // 如果长度是偶数 console.log("中位数为: "+(concat[length / 2]+concat[(length / 2) - 1]) / 2); } } arr1 = [1, 4, 7, 9,2] medianof2Arr(arr1);
arr1 = [1, 4, 7, 9] medianof2Arr(arr1);
[Related recommendations: javascript learning Tutorial】
The above is the detailed content of How to find the median of an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!