Skip to content

Commit 33f2345

Browse files
committed
Mean median mode algorithm
1 parent 96e2b7e commit 33f2345

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Algorithm/meanMedianMode.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
function meanMedianMode(arr) {
2+
return {
3+
mean: getMean(arr),
4+
median: getMedian(arr),
5+
mode: getMode(arr)
6+
};
7+
}
8+
9+
function getMean(arr) {
10+
let sum = 0;
11+
12+
arr.forEach(num => {
13+
sum += num;
14+
});
15+
16+
let mean = sum / arr.length;
17+
return mean;
18+
}
19+
20+
function getMedian(arr) {
21+
arr.sort(function(a, b) {
22+
return a - b;
23+
});
24+
let median;
25+
26+
if (arr.length % 2 !== 0) {
27+
median = arr[Math.floor(arr.length / 2)];
28+
} else {
29+
let mid1 = arr[arr.length / 2 - 1];
30+
let mid2 = arr[arr.length / 2];
31+
median = (mid1 + mid2) / 2;
32+
}
33+
34+
return median;
35+
}
36+
37+
function getMode(arr) {
38+
let modeObj = {};
39+
40+
arr.forEach(num => {
41+
if (!modeObj[num]) modeObj[num] = 0;
42+
modeObj[num]++;
43+
});
44+
45+
let maxFrequency = 0;
46+
let modes = [];
47+
for (let num in modeObj) {
48+
if (modeObj[num] > maxFrequency) {
49+
modes = [num];
50+
maxFrequency = modeObj[num];
51+
} else if (modeObj[num] === maxFrequency) modes.push(num);
52+
}
53+
54+
if (modes.length === Object.keys(modeObj).length) modes = [];
55+
56+
return modes;
57+
}
58+
59+
meanMedianMode([1, 2, 3, 4, 5, 4, 6, 1]); // { mean: 3.25, median: 3.5, mode: [ '1', '4' ] }
60+
61+
meanMedianMode([9, 10, 23, 10, 23, 9]); // mean: 14, median: 10, mode: [] }

0 commit comments

Comments
 (0)