<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
Tuesday, August 20, 2019
Subscribe to:
Post Comments
(
Atom
)
Looks like all your recent problems can be fixed by introducing lodash
ReplyDelete