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
Asked
Active
Viewed 964 times
2
-
1http://stackoverflow.com/a/33470127/3993662 – baao Nov 02 '15 at 03:11
1 Answers
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
-
-
-
The output won't be displayed on the screen. I used `console.log` so open your console. If you want to display average value on the screen use `document.write`. – Matt Komarnicki Nov 02 '15 at 03:25
-
It Worked! Thanks Alot For Your Help...I'm Having More Doubts in javascript..I will get back here for help! – Manoj Karthik Nov 02 '15 at 03:28
-
Glad I could help. Please, up vote my answer if it was useful. Thanks. – Matt Komarnicki Nov 02 '15 at 03:29