0

Like the title suggests, what I need to do is calculating the average of an array using for-loop. And by average I mean (a+b+c+d+e)/5=average.

That's what I need to do in text, since I'm new at javascript I don't quite know how to execute this. Any ideas?

Also, if you think this question doesn't belong here or is stupid, please direct me to somewhere where I can find this information, I'm just trying to learn here.

function test(arr) {


}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Andrew P
  • 1,487
  • 5
  • 17
  • 18

5 Answers5

5
function average(items) {
  var sum = 0;
  var count = items.length;
  for (i=0; i<count; i++) {
    sum += items[i];
  }
  return sum/count;
}

Or if you want average() to be available as a method on arrays:

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

Usage:

[1,2,3,4,5].average(); // 3
Panagiotis Panagi
  • 9,927
  • 7
  • 55
  • 103
  • @AndrewP Inside the loop, we add the values one-by-one into an accumulator (`average` variable). After the loop we divide the sum with the number of amounts. – Panagiotis Panagi Jan 03 '14 at 14:47
1

Here is a post with the response to your answer.

Array Sum and Average

Also check this link about for loop in Javascript:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in

Community
  • 1
  • 1
Aerilys
  • 1,628
  • 1
  • 16
  • 22
1

Just iterate over the values, sum them up, and return the value of sum, divided by the number of entries.

function test (arr) {
  for (var i=0,sum=0;i<arr.length;i++) {
    sum += arr[i];
  }
  return sum / i;
}
Moritz Roessler
  • 8,542
  • 26
  • 51
0

This should help

var nCtrr = 0, nSum = 0, nAvg = 0;
var arNum = [1, 2, 3, 4, 5];
for ( nCtr in arNum ) {

    nSum += arNum[ nCtr ];
    nCtr += 1;

}
nAvg = nSum/arNum.length;
alert( nAvg );

JSFiddle

0

Suggestion, none of the answers here check for length === 0, you'll be dividing by zero in some situation in the future. I suggest you always check mathematical boundary conditions. The related article had one response which caught that (https://stackoverflow.com/a/18234568/987044).

Here is another example if you want to be safe. http://jsfiddle.net/ledlogic/syn74/

var nothing = null;
var empty = [];
var items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; // 20 sider
function average(items) {
    if (!items) {
        return 0;
    }
    var sum = 0,
        count = 0;
    // for large arrays, faster to go down.
    for (var count = items.length, i = count - 1; i >= 0; i--) {
        sum += items[i];
    }
    return count ? sum / count : 0;
}

alert(nothing + ":" + average(nothing) + "\r" + empty + ":" + average(empty) + "\r" + items + ":" + average(items) + "\r");

The math.js library, mean.js also does array length checking.

Community
  • 1
  • 1
ledlogic
  • 774
  • 1
  • 9
  • 19