-
Notifications
You must be signed in to change notification settings - Fork 0
/
MeanMedianMode.js
74 lines (62 loc) · 1.7 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
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Mean, median, mode
*/
function average(arr) {
let avg = 0;
let sum = 0;
arr.forEach((number) => {
sum += number;
});
avg = sum / arr.length;
return avg;
}
function median(arr) {
arr.sort((a, b) => {
return a - b;
});
if (arr.length % 2 === 0) {
return average([arr[arr.length / 2], arr[arr.length / 2 - 1]]);
} else {
console.log("here");
return arr[Math.floor(arr.length / 2)];
}
}
// console.log(median([2, 4, 6, 8, 10]));
// console.log(median([15, 22, 9, 31, 18]));
// console.log(median([7, 14, 21, 42, 35, 28]));
function mode(arr) {
let maximumValue = 0;
let maximumKey = 0;
numberCounter = {};
arr.forEach((num) => {
if (!numberCounter[num]) {
numberCounter[num] = 1;
} else {
numberCounter[num]++;
}
});
//different methods for looping through the dict
//1
// for(const key of numberCounter){
// console.log(key,numberCounter[key]);
// }
//2
for (const [key, value] of Object.entries(numberCounter)) {
if (value > maximumValue) {
maximumValue = value;
maximumKey = key;
}
}
//BUT, what if there is no mode, all occur the same # of times?
//something like this:
const values = Object.values(numberCounter);
const allSame = values.every(value => value === values[0]);
if(allSame){
return ("none")
}
return maximumKey;
}
console.log(mode([1, 2, 2, 3]));
console.log(mode([3, 5, 3, 7, 9]));
console.log(mode([12, 15, 12, 18, 20]));
console.log(mode([8, 14, 22, 30, 36]));