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 to get your results.

The below code is based on the Quartile calculator logic used in two Websites: www.mathhack.net and www.mathisfun.com

Javascript Code:

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);

// MEDIAN LOGIC
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;
}

// GET VALUES FROM ARRAY
medianX(q1Arr);
Q1=median;
medianX(q2Arr);
Q2=median;
medianX(q3Arr);
Q3=median;

// PRINT Q1, Q2, Q3 Array
console.log(q1Arr, q2Arr, q3Arr);
// PRINT Q1, Q2, Q3 Value
console.log(Q1,Q2,Q3);

Comments

Popular posts from this blog

About 12 Alwars

Post thumbnails from external URLs don’t appear in Blogger. How to resolve?