JavaScript 如何获取数字数组的中位数
在本文中,我们将看到如何使用JavaScript找到数组的中位数。中位数是给定一组数字或数据中的中间值。
示例:
Input arr1 : [1 4 7 9]
Output : 5.5
Explanation : The median of the two sorted array is
the middle elements which is 5 if the
arrayLength =arr1.length + arr2.length is odd
if the array length is even then it will be
the average of two number
Input: arr1 : [5 3 1 8 90]
Output: 5
Explanation : The median is average of two number
because the array.length is even for this case.
方法1
首先,我们对数组进行排序,然后找到数组的长度。如果数组长度为偶数,则中位数将是arr[(arr.length)/2] +arr[((arr.length)/2)+1]
。如果数组长度为奇数,则中位数将是中间元素。
示例:
<script>
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 length is odd
console.log(concat[(length / 2) - .5])
return concat[(length / 2) - .5]
}
else {
console.log((concat[length / 2]
+ concat[(length / 2) - 1]) / 2);
return (concat[length / 2]
+ concat[(length / 2) - 1]) / 2;
}
}
arr1 = [1, 4, 7, 9]
medianof2Arr(arr1)
</script>
输出:
5.5
方法2
这里我们首先创建了变量 middle ,它具有中间值,无论数组的长度是奇数还是偶数。现在,在这之后,我们通过避免变异(mutation)来对数组进行排序。变异意味着将对象名更改为另一个对象名或将对象传递给另一个对象称为变异。
这可以用 引用数据 类型来完成,这些类型包括 数组, 对象 等。所以现在避免这样做。之后,如果数组的长度是偶数,则数组中有两个值在位置 arr((arr.length)/2) + arr(((arr.length)/2) +1)。然后取这两个数的平均值,并作为中位数返回。
示例:
<script>
function median_of_arr(arr) {
const middle = (arr.length + 1) / 2;
// Avoid mutating when sorting
const sorted = [...arr].sort((a, b) => a - b);
const isEven = sorted.length % 2 === 0;
return isEven ? (sorted[middle - 1.5]
+ sorted[middle - 0.5]) / 2 :
sorted[middle - 1];
}
var arr = [1, 4, 7, 9];
console.log(median_of_arr(arr));
</script>
输出:
5.5