Javascript Array median()

Description

Javascript Array 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  w  w  w .j  a  va 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

Javascript Array median()

Array.prototype.median = function() {
  var values = this;
    values.sort( function(a,b) {return a - b;} );
 
    var half = Math.floor(values.length/2);
 
    if(values.length % 2){
        return values[half];
    } else {/*from  w  w w .  ja va  2 s  .c  o m*/
        return (values[half-1] + values[half]) / 2.0;
    }
};

Javascript Array median()

Array.prototype.median = function() {
  this.sort();// w  ww.j  a v a2  s  .  com
  
  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];
  }
};



PreviousNext

Related