-2

Hello we have a problem in class to get the average out of a array of even numbers that we generate and I can't seem to get it to work.

var theArray = [];
for (var i = 1; i <= 100; i++) {
  if (i % 2 == 0) {
    theArray.push(i);
  }
}
var total1 = 0;

for (var element in theArray) {
  total1 += theArray[element];
  total1 / 50;
}

document.write(total1);

This is the code, what am I doing wrong as I don't the array is even filling up. Any help will be great as the professor doesn't answer email very fast.

Thanks!

RobG
  • 142,382
  • 31
  • 172
  • 209
J Fletcher
  • 35
  • 9
  • `=` is for assignment, `==` is for comparison. Also `total1 / 50;` does nothing. – Pointy Feb 25 '17 at 00:07
  • 1
    just move `total1 / 50` after your for loop, and assign it to itself like so: `total1 = total1 / 50` – mhodges Feb 25 '17 at 00:07
  • 1
    Also don't use `for ... in` on arrays. Use a `for` loop with an index variable (like your first `for` loop) or use `.forEach()`. – Pointy Feb 25 '17 at 00:08
  • Have a look at [*Array Sum and Average*](http://stackoverflow.com/questions/10359907/array-sum-and-average). – RobG Feb 25 '17 at 00:33

2 Answers2

0

You can use a reducer function to sum all of the elements, and then divide by the total at the end as demonstrated below. Note that your i % 2 = 0 should use an ==.

var theArray = [];

// fill/set up array
for (var i = 1; i <= 100; i++) {
  if(i % 2 == 0) {
    theArray.push(i);
  }
}

// calculate total
var total = theArray.reduce(function (total, element) {
  return total + element;
}, 0);

// calculate average
var average = total / theArray.length;

document.write(average);
Liam Gray
  • 1,089
  • 9
  • 16
0

You don't need the array:

total = 0;
number_of_numbers = 0;
for (var i = 1; i <= 100; i++) {
    if(i % 2 == 0) {
        total += i;
        number_of_numbers += 1;
    }
}
document.write(total/number_of_numbers);

But if you have to:

var theArray = [];
for (var i = 1; i <= 100; i++) {
    if(i % 2 == 0) {
        theArray.push(i);
    }
}
var total = 0;
for(var i in theArray) { total += theArray[i]; }
document.write(total/theArray.length);
Boris
  • 11,373
  • 2
  • 33
  • 35