Created
July 13, 2016 07:16
-
-
Save stekhn/254c3b82ac5637a8eebe4f5683c0f110 to your computer and use it in GitHub Desktop.
Weighted median in JavaScript
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
| function weightedMedian(values, weights) { | |
| var midpoint = 0.5 * sum(weights); | |
| var cumulativeWeight = 0; | |
| var belowMidpointIndex = 0; | |
| var sortedValues = []; | |
| var sortedWeights = []; | |
| values.map(function (value, i) { | |
| return [value, weights[i]]; | |
| }).sort(function (a, b) { | |
| return a[0] - b[0]; | |
| }).map(function (pair) { | |
| sortedValues.push(pair[0]); | |
| sortedWeights.push(pair[1]); | |
| }); | |
| if (sortedWeights.some(function (value) { return value > midpoint; })) { | |
| return sortedValues[sortedWeights.indexOf(Math.max.apply(null, sortedWeights))]; | |
| } | |
| while (cumulativeWeight <= midpoint) { | |
| belowMidpointIndex++; | |
| cumulativeWeight += sortedWeights[belowMidpointIndex - 1]; | |
| } | |
| cumulativeWeight -= sortedWeights[belowMidpointIndex - 1]; | |
| if (cumulativeWeight - midpoint < Number.EPSILON) { | |
| var bounds = sortedValues.slice(belowMidpointIndex - 2, belowMidpointIndex); | |
| return sum(bounds) / bounds.length; | |
| } | |
| return sortedValues[belowMidpointIndex - 1]; | |
| } | |
| function sum(arr) { | |
| return arr.reduce(function (previous, current) { | |
| return previous + current; | |
| }); | |
| } | |
| weightedMedian([251, 360, 210], [0.1, 0.5, 0.7]); | |
| // => 210 | |
| weightedMedian([251, 360, 210, 340], [0.1, 0.5, 0.7, 0.6]); | |
| // => 295.5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! Going to try this out in my finance app. Or something similar...