Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active October 15, 2017 01:21
Show Gist options
  • Select an option

  • Save jialinhuang00/db8c39a539fc3dd661b51ba364241b43 to your computer and use it in GitHub Desktop.

Select an option

Save jialinhuang00/db8c39a539fc3dd661b51ba364241b43 to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
1.3 function used to calculate: mean, median, mode.
2.writing another function to package them.
3.MODE: if there is no number repeated, return false.
3.MODE: maybe there is not only one mode.
the reference is from UdemyCourse: LearningAlgorithmsInJavascriptFromScratch
-----------------------------------------------------------------------------*/
function meanMedianMode(arr) {
return {
mean: getMean(arr),
median: getMedian(arr),
mode: getMode(arr),
};
}
meanMedianMode([1, 4, 21, 23, 24, 32, 33, 43]);
function getMean(arr) {
return (
arr.reduce((a, b) => {
return a + b;
}) / arr.length
);
}
function getMedian(arr) {
// sorting in order
// if only using sort() default, 1000 may ordered first but not 40
arr = arr.sort((a, b) => {
return a - b;
});
if (arr.length % 2 === 0)
return (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
else {
return arr[(arr.length - 1) / 2];
}
}
function getMode(arr) {
// create a dict
var countObj = {};
arr.forEach(n => {
if (!countObj[n]) {
countObj[n] = 0;
}
countObj[n]++;
});
var modes = [];
var maxFrequency = 0;
// iterate it to find the max frequency
for (var n in countObj) {
if (countObj[n] > maxFrequency) {
modes = [n];
maxFrequency = countObj[n];
} else if (countObj[n] === maxFrequency) {
modes.push(n);
}
}
// every element is mode means no mode.
if (modes.length === Object.keys(countObj).length) {
modes = false;
}
return modes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment