-
Notifications
You must be signed in to change notification settings - Fork 1
/
MeanMedianMode.js
45 lines (40 loc) · 930 Bytes
/
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
function meanMedianMode (arr) {
return {
mean: getMean(arr),
median: getMedian(arr),
mode: getMode(arr)
}
}
function getMean (arr) {
let sum = arr.reduce((prev, next) => prev + next, 0)
return sum / arr.length
}
function getMedian (arr) {
arr.sort((a, b) => a - b)
const len = arr.length
if (len % 2 !== 0) {
return arr[Math.floor(len / 2)]
} else {
return (arr[len / 2 - 1] + arr[len / 2]) / 2
}
}
function getMode (arr) {
let modeObj = {}
arr.forEach(num => {
if (!modeObj[num]) modeObj[num] = 0
modeObj[num]++
})
let maxFreq = 0
let mode = []
for (let num in modeObj) {
if (modeObj[num] > maxFreq) {
mode = [num]
maxFreq = modeObj[num]
} else if (modeObj[num] === maxFreq) {
mode.push(modeObj[num])
}
}
if (mode.length === Object.keys(modeObj).length) mode = []
return mode
}
console.log(meanMedianMode([9, 10, 23, 10, 23, 9]))