Last active
August 18, 2019 04:11
-
-
Save dsetzer/41580d1f317cca816bb9df0b4dc6f5b1 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
let values = [2, 56, 3, 41, 0, 4, 100, 23]; | |
values.sort((a, b) => a - b); | |
let median = (values[(values.length - 1) >> 1] + values[values.length >> 1]) / 2 | |
// median = 13,5 | |
/*for finding average you can combine map and reduce at the same time: | |
*/ | |
let avg = values.map((c, i, arr) => c / arr.length).reduce((p, c) => c + p); | |
/* | |
Also median for even number of elements should be sum of two middle numbers divided by 2. So in this case median should be (4 + 23) / 2 = 13.5 and not 23. | |
Here is the logic for calculation median: | |
*/ | |
function median(arr) { | |
arr.sort((a, b) => a - b); | |
var pivot = Math.floor(arr.length / 2); | |
return arr.length % 2 ? arr[pivot] : (arr[pivot - 1] + arr[pivot]) / 2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment