Nodejs Array Median median()

Here you can find the source of median()

Method Source Code

// 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

Related

  1. median()
    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];
    
  2. median()
    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
    };
    
  3. median()
    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];
    };
    
  4. median()
    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