Here you can find the source of median()
// Write a method that returns the median of elements in an array // If the length is even, return the average of the middle two elements Array.prototype.median = function() { let mid = Math.floor(this.length / 2); if (this.length % 2 === 0){ return (this[mid] + this[mid+1]) / 2; } else {/*from ww w .j av a 2 s. c o m*/ return this[mid]; } }; console.log([1,2,3,4,5,6].median()); // 4.5 console.log([1,2,3,4,5].median()); // 3
Array.prototype.median = function() { var middle = Math.floor(this.length / 2); var evenMiddle = (this[middle-1] + this[middle]) / 2; if (this.length % 2 == 0) { return evenMiddle; } else { return this[middle];
Array.prototype.median = function() { var length = this.length; if(length % 2 != 0){ return this[Math.floor(length/2)]; } else { return (this[(length/2) - 1] + this[length/2])/2 };
Array.prototype.median = function() { this.sort(); if (this.length % 2 === 0) { var middle = this.length / 2 - 1; return (this[middle] + this[middle + 1]) / 2; } else { var middle = Math.floor(this.length / 2); return this[middle]; };
Array.prototype.median = function() { if((this.length - 1) % 2 == 0){ return this[(this.length - 1) / 2]; else { var eOne = this[Math.floor((this.length - 1) / 2)] var eTwo = this[Math.ceil((this.length - 1) / 2)] return (eOne + eTwo) / 2