Nodejs Array Average findAverage()

Here you can find the source of findAverage()

Method Source Code

/*//from w w w .  ja  v  a  2 s  .c om
ANSWER
It takes into account findAverage method which comes from prototype.

EXPLANATION
for-in loop loops through keys of all properties of object.
By default it also loops through keys coming from prototype.
*/

Array.prototype.findAverage = function(){
    var length = this.length;
    var average = 0;
    for(var i = 0; i < length; i++){
        var value = this[i];
        average += value;
    }
    return average / length;
}

var numbers = [1, 34, 5, 17, 2, 3, 90];

var average = numbers.findAverage();

Related

  1. avg()
    Array.prototype.avg = function(){
      return this.sum() / this.length;
    };
    Array.prototype.sum = function(){
      for (var i = 0, sum = 0 ; i != this.length; ++i) {
        var n = this[i];
        if(!isNaN(n)) {
          sum += n*1;
      return sum;
    };
    
  2. avg()
    Array.prototype.avg = function() {
      var av, num, _i, _len;
      av = 0;
      for (_i = 0, _len = this.length; _i < _len; _i++) {
        num = this[_i];
        av = av + num;
      return av / this.length;
    };
    ...
    
  3. avg()
    Array.prototype.avg = function() {
      var av = 0;
      var cnt = 0;
      var len = this.length;
      for (var i = 0; i < len; i++) {
        var e = +this[i];
        if(!e && this[i] !== 0 && this[i] !== '0') e--;
        if (this[i] == e) {av += e; cnt++;} }
      return av/cnt;
    ...
    
  4. avg()
    Array.prototype.avg = function () {
      var sum=0;
      var drops=this.drops();
      for (var i = 0; i < this.length; i++)
        if (+this[i] !== 0)
          sum += +this[i];
      return (sum/(this.length-drops));
    
  5. findAverage()
    Array.prototype.findAverage = function(){
        var length = this.length;
        var average = 0;
        for(var i = 0; i < length; i++){
            var value = this[i];
            average += value;
        return average / length;
    var numbers = [1, 34, 5, 17, 2, 3, 90];
    var average = numbers.findAverage();
    for(key in numbers) {
        var message = key + ' = ' + numbers[key];
        if(numbers[key] < average){
            message += ' \\/'
        else {
            message += ' /\\'
        console.log(message);