728x90 AdSpace

Latest News
Monday, October 20, 2014

Calculate Quartile : Q1, Q3 and Median (Q2) in Javascript

Are you want to calculate Q1, Q3 and Median (Q2) in Javascript. Just use the code shown below get your results.
The below code is based on the Quartile calculator logic used in two Websites: www.mathhack.net and www.mathisfun.com

<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script>
values = [1, 3, 3, 4, 5, 6, 6, 7, 8, 8];
Q1=Q2=Q3=0;

/*
//HACK MATH LOGIC
//http://www.hackmath.net/en/calculator/quartile-q1-q3

q1Arr = (values.length % 2 == 0) ? values.slice(0, (values.length / 2) + 1) : values.slice(0, Math.floor(values.length / 2) + 1);
q2Arr =  values;
q3Arr = (values.length % 2 == 0) ? values.slice( (values.length/2) - 1, values.length) : values.slice(Math.ceil(values.length / 2) - 1, values.length);
*/

//MATH IS FUN LOGIC
//http://www.mathsisfun.com/data/quartiles.html

q1Arr = (values.length % 2 == 0) ? values.slice(0, (values.length / 2)) : values.slice(0, Math.floor(values.length / 2));
q2Arr =  values;
q3Arr = (values.length % 2 == 0) ? values.slice((values.length / 2), values.length) : values.slice(Math.ceil(values.length / 2), values.length);
medianX(q1Arr);
Q1=median;
medianX(q2Arr);
Q2=median;
medianX(q3Arr);
Q3=median;
function medianX(medianArr) {
count = medianArr.length;
median = (count % 2 == 0) ? (medianArr[(medianArr.length/2) - 1] + medianArr[(medianArr.length / 2)]) / 2:medianArr[Math.floor(medianArr.length / 2)];
return median;
}
console.log(q1Arr, q2Arr, q3Arr);
console.log(Q1,Q2,Q3);
</script>
</head>
<body>
</body>
</html>
  • Blogger Comments
  • Facebook Comments

0 comments:

Post a Comment

Item Reviewed: Calculate Quartile : Q1, Q3 and Median (Q2) in Javascript Rating: 5 Reviewed By: Thiruvikraman Govindarajan