Last active
February 25, 2019 03:55
-
-
Save okovalov/25c70be80899eb06b13add810ff39a11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getMedian = arr => { | |
const arrLen = arr.length | |
if (arrLen % 2 !== 0) { | |
return arr[Math.floor(arrLen / 2)] | |
} else { | |
const m1 = arr[(arrLen / 2) - 1] | |
const m2 = arr[arrLen / 2] | |
return (m1 + m2) / 2 | |
} | |
} | |
const getModes = hash => { | |
let modes = [] | |
let maxFrequency = 0 | |
for(let number in hash) { | |
const currentFreq = hash[number] | |
if (currentFreq > maxFrequency) { | |
modes = [number] | |
maxFrequency = currentFreq | |
} else if (currentFreq === maxFrequency) { | |
modes.push(number) | |
} | |
} | |
if (modes.length === Object.keys(hash).length) modes = [] | |
return modes | |
} | |
const meanMedianMode = arr => { | |
arr.sort( (a,b) => a - b ) | |
let sum = 0 | |
let hash = {} | |
for(let idx in arr) { | |
const num = arr[idx] | |
sum += num | |
if (!hash[num]) hash[num] = 0 | |
hash[num]++ | |
} | |
return { | |
mean: sum / arr.length, | |
median: getMedian(arr), | |
modes: getModes(hash) | |
} | |
} | |
const arr = [1,2,3,4,5,4,6,1] // 3.25, 3.5, [1,4] | |
const arr2 = [9,10,23,10,23,9] // 14, 10, [] | |
const result = meanMedianMode(arr) | |
const result2 = meanMedianMode(arr2) | |
console.log(result) | |
console.log(result2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment