-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
60 lines (48 loc) · 1.21 KB
/
index.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
class meanMedianMode {
constructor(arr) {
this.arr = arr;
}
getMean(arr) {
return arr.reduce((acc, num) => acc + num) / arr.length;
}
getMedian(arr) {
arr.sort((a, b) => a - b);
let median;
const isOddLength = arr.length % 2 !== 0;
if (isOddLength) {
median = arr[Math.floor(arr.length / 2)];
} else {
const mid1 = arr[arr.length / 2 - 1];
const mid2 = arr[arr.length / 2];
median = (mid1 + mid2) / 2;
}
return median;
}
getMode(arr) {
const modeObj = arr.reduce((obj, num) => {
if (!obj[num]) obj[num] = 0;
obj[num]++;
return obj;
}, {});
let maxFrequency = 0;
return Object.keys(modeObj)
.reduce((acc, num) => {
if (modeObj[num] > maxFrequency) {
acc = [num];
maxFrequency = modeObj[num];
} else if (modeObj[num] === maxFrequency) {
acc.push(num);
}
return acc;
}, [])
.filter((num, i, arr) => arr.length !== Object.keys(modeObj).length);
}
getMeanMedianMode() {
return {
mean: this.getMean(this.arr),
median: this.getMedian(this.arr),
mode: this.getMode(this.arr),
};
}
}
export default meanMedianMode;