Tuesday, August 20, 2019

[JavaScript][Example] get median from a list of numbers

<script>
const ROUND_TO_FIXED = 2;
function _stringToList(string){
    return string.split(",");
}
function _roundToFixed(num){
    return Number(parseFloat(num).toFixed(ROUND_TO_FIXED));
}
function getSampleMedian(string){
    var sourceList  = _stringToList(string);
    var sortedList  = sourceList.sort();
    var medianPos   = null;
    var medianIndex = null;
    var median      = 0;
    if(sortedList.length%2 === 0){
        medianPos   = (sortedList.length+1)/2;
        medianIndex = medianPos-1;
        median      = ( parseFloat(sortedList[Math.ceil(medianIndex)]) +
                        parseFloat(sortedList[Math.floor(medianIndex)]) ) /2;
    }else{
        medianPos   = (sortedList.length+1)/2;
        medianIndex = medianPos -1;
        median      = sortedList[medianIndex];
    }
    return median;
}
var testValue = "1,2,3,5,1,2,6";
console.log(getSampleMedian(testValue));
</script>

Result :
2

1 comment :

  1. Looks like all your recent problems can be fixed by introducing lodash

    ReplyDelete