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
1 Answer
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));
}
5 Comments
Matt Komarnicki
Check my answer. It's working.
Manoj Karthik
I'm Unable To See Output Though I Given The Same Code In <script> Tag
Matt Komarnicki
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.Manoj Karthik
It Worked! Thanks Alot For Your Help...I'm Having More Doubts in javascript..I will get back here for help!
Matt Komarnicki
Glad I could help. Please, up vote my answer if it was useful. Thanks.