2

I Want To Calculate Average Value Of Array Elements Using Java Script. I am an beginner in Java Script, So Please Give me the easiest & understandable code

Manoj Karthik
  • 161
  • 1
  • 1
  • 6

1 Answers1

1

Assuming that all items in your array are numbers, loop through them, and sum them. Once you have a sum of all items, divide this figure by number of items (your_array.length) and then you'll get your average.

Show your existing code, what you have done so far?

Not tested, pseudo code:

var array = [1, 6, 43, 2, 8];
var sum = 0;

for (var i = 0; i < array.length; i++) {
    sum += parseInt(array[i]);
}

if (array.length > 0) {
    console.log('Average is ' + (sum / array.length));  
}
Matt Komarnicki
  • 5,198
  • 7
  • 40
  • 92