Home > Web Front-end > JS Tutorial > body text

How to find the median of an array in JavaScript

青灯夜游
Release: 2022-02-18 16:52:28
Original
6488 people have browsed it

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]".

How to find the median of an array in JavaScript

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);
Copy after login

How to find the median of an array in JavaScript

arr1 = [1, 4, 7, 9]
medianof2Arr(arr1);
Copy after login

How to find the median of an array in JavaScript

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!