Last active
November 28, 2019 05:35
-
-
Save br3nt/f201921cd89a9448c78bfb1965addcd6 to your computer and use it in GitHub Desktop.
JS median and splitMedian functions
This file contains 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
function medianSplit(array) { | |
let midPoint = array.length / 2 | |
array = array.sort((a, b) => a - b) | |
let firstHalf = array.slice(0, Math.floor(midPoint)) | |
let middle = array.slice(Math.floor(midPoint), Math.ceil(midPoint))[0] | |
let lastHalf = array.slice(Math.ceil(midPoint), array.length) | |
return [firstHalf, middle, lastHalf] | |
} | |
function median(array) { | |
let [firstHalf, middle, lastHalf] = medianSplit(array) | |
if (middle) return middle | |
return (firstHalf[firstHalf.length - 1] + lastHalf[0]) / 2 | |
} | |
// example | |
let [firstHalf, middle, lastHalf] = medianSplit([1, 2, 3, 4, 5, 6, 7]) | |
let m = median([1, 2, 3, 4, 5, 6, 7]) | |
// remove outliers using IQR (see: https://fr.mathworks.com/matlabcentral/cody/problems/42485-eliminate-outliers-using-interquartile-range) | |
let fullSample = [1, 2, 3, 4, 5, 6, 7] | |
[firstHalf, middle, lastHalf] = medianSplit(fullSample) | |
let interquartileRange = median(lastHalf) - median(firstHalf) | |
let outlierThreshhold = 1.5 * interquartileRange | |
let fullSampleAvg = avarage(fullSample) | |
let sample = fullSample.filter(p => p - fullSampleAvg <= outlierThreshhold) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment