-
Notifications
You must be signed in to change notification settings - Fork 1
/
meanMedianMode.js
61 lines (50 loc) · 1.26 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
let getMean = (myArray) => {
let sum = 0;
myArray.forEach(number => sum += number);
return sum/myArray.length;
};
let getMedian = (myArray) => {
myArray.sort((a, b) => a - b);
let arrayLength = myArray.length;
if (arrayLength % 2 != 0) {
return myArray[parseInt(arrayLength / 2)];
} else {
return (myArray[arrayLength/2] + myArray[(arrayLength/2) - 1]) / 2;
}
};
let getMode = (myArray) => {
let myMap = {};
let mode = [], frequency = -1;
myArray.forEach((number) => {
if (!myMap[number]) {
myMap[number] = 0;
}
myMap[number]++;
});
for (let num in myMap) {
if (myMap[num] >= frequency) {
if (myMap[num] == frequency) {
mode.push(num);
} else {
frequency = myMap[num];
mode = [];
mode.push(num);
}
}
}
return mode;
};
let getMeanMedianMode = (myArray, cb) => {
let myObject = {
mean: getMean(myArray),
median: getMedian(myArray),
mode: getMode(myArray)
};
return cb(null, myObject);
};
getMeanMedianMode([1, 2, 3, 4, 5, 4, 6, 1], (err, myObject) => {
if (err) {
} else {
console.log(myObject);
}
});