Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

the median of the list javascript

function median(values){
    if(values.length === 0) throw new Error("No inputs");
    values.sort(function(a,b){
      return a-b;
    });
    var half = Math.floor(values.length / 2);
    if (values.length % 2)
      return values[half];
    return (Number(values[half - 1]) + Number(values[half])) / 2;
}

console.log(median([5, 6, 50, 1, -5])) // 5
console.log(median([1, 2, 3, 4, 5])); // 3
 
PREVIOUS NEXT
Tagged: #median #list #javascript
ADD COMMENT
Topic
Name
8+6 =