-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMeanMedianMode.js
61 lines (50 loc) · 1.16 KB
/
MeanMedianMode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
function meanMedianMode(array) {
return {
mean: getMean(array),
median: getMedian(array),
mode: getMode(array)
}
}
function getMean(array) {
var sum = 0;
array.forEach(num => {
sum += num;
});
var mean = sum / array.length;
return mean;
}
function getMedian(array) {
array.sort(function(a, b){return a-b});
var median;
if (array.length % 2 !== 0) {
median = array[Math.floor(array.length / 2)];
}
else {
var mid1 = array[(array.length / 2) - 1];
var mid2 = array[array.length / 2];
median = (mid1 + mid2) / 2;
}
return median;
}
function getMode(array) {
var modeObj = {};
// create modeObj
array.forEach(num => {
if (!modeObj[num]) modeObj[num] = 0;
modeObj[num]++;
});
// create array of mode/s
var maxFrequency = 0;
var modes = [];
for (var num in modeObj) {
if (modeObj[num] > maxFrequency) {
modes = [num];
maxFrequency = modeObj[num];
}
else if (modeObj[num] === maxFrequency) modes.push(num);
}
// if every value appears same amount of times
if (modes.length === Object.keys(modeObj).length) modes = [];
return modes;
}
meanMedianMode([9,10,23,10,23,9]);