Javascript Array total()

Description

Javascript Array total()


var pry = require('pryjs');

Array.prototype.total = function(){
  var total = 0;//from www.j  a  va 2  s .  c o m
  for(i=0; i < this.length; i++){
    total = this[i] +total
  }
  return total;
}

Array.prototype.average = function(){
  return (this.total()/ this.length)
}

Array.prototype.median = function(){
  var a = this.sort()
  var half = Math.floor(a.length/2)

  if(a.length%2){
    return a[half]
  } else {
    return (a[half-1] + a[half])/2
  }

}
Array.prototype.mode = function(){
  var numbers = {};
  var frequency = 0;
  var mode = {};
  this.forEach(function findMode(num){
    numbers[num] = (numbers[num] || 0) +1;

    if(frequency < numbers[num]){
      frequency = numbers[num];
      mode[num] = numbers[num]
    };
  });
  return mode
};

Javascript Array total()

Array.prototype.total = function() {
  return this.reduce(function(a,b){
    return a + b;
  })/*ww  w .java  2s .com*/
};

Array.prototype.mean = function() {
  var length = this.length;
  return this.total()/length;
};

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.mode = function() {
  var numHash = [];
  for(var i = 0; i < this.length; i++){
    if(numHash[this[i]] == undefined){
      numHash[this[i]] = 1;
    } else {
      numHash[this[i]] ++;
    }
  }

  return Object.keys(numHash).reduce(function(a,b){
    var max = numHash[a] > numHash[b] ? a:b ;
  });

  // var modeArray = [];
  // for(key in numHash){
  //   modeArray.push(numHash[key]);
  // }

  // var max = Math.max(...modeArray);
  // for(key in numHash){
  //   if(numHash[key] == max){
  //     return key = numHash[key];
  //   }
  // }

};



PreviousNext

Related