Last active
October 30, 2022 04:43
-
-
Save seanghay/3969d85477a8c75fd472592fe739b35e to your computer and use it in GitHub Desktop.
Mean, Median & Mode functions using JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An average of a set of numbers. | |
* @param {number[]} values | |
* @returns {number} | |
*/ | |
export function mean(...values) { | |
if (values.length === 0) return; | |
return values.reduce((a, b) => a + b, 0) / values.length; | |
} | |
/** | |
* A middle number of a set numbers. | |
* e.g. [1, 2, 3], median = 2 | |
* e.g. [1, 2, 3, 4], median = mean(2, 3) = 2.5 | |
* @param {number[]} values | |
* @returns {number} | |
*/ | |
export function median(...values) { | |
const l = values.length; | |
if (l === 0) return; | |
values = values.sort(); | |
if (l % 2 === 0) { | |
return mean(values[(l / 2) - 1], values[(l / 2)]) | |
} else { | |
return values[(l - 1) / 2]; | |
} | |
} | |
/** | |
* Find most occurring numbers. | |
* e.g. [1, 2, 3, 4, 3], mode = 3 | |
* e.g. [1, 1, 2, 2, 3, 4], mode = [1, 2] | |
* e.g. [1, 2, 3], mode = undefined | |
* @param {number[]} values | |
* @returns {number[]} | |
*/ | |
export function mode(...values) { | |
const l = values.length; | |
if (l === 0) return; | |
const map = new Map(); | |
let sum = 0; | |
for (const value of values) { | |
if (map.has(value)) { | |
map.set(value, map.get(value) + 1); | |
continue; | |
} | |
sum++; | |
map.set(value, 1); | |
} | |
// no-mode | |
if (sum === l) { | |
return []; | |
} | |
let maxCount = 0; | |
let modes = []; | |
for (const [number, count] of map.entries()) { | |
if (count > maxCount) { | |
maxCount = count; | |
modes = [number]; | |
continue; | |
} | |
if (count === maxCount) { | |
modes = [ | |
...modes, | |
number, | |
]; | |
} | |
} | |
return modes | |
} | |
console.log('mean:', mean(1, 2, 3, 4, 5)) | |
console.log('median:', median(1, 2, 3, 4, 5)) | |
console.log('mode:', mode(1, 2, 3, 4, 5, 6, 7, 8, 1, 2)) | |
// => mean: 3 | |
// => median: 3 | |
// => mode: [ 1, 2 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment