Home >Web Front-end >JS Tutorial >How to Calculate the Sum and Average of Array Elements in JavaScript?

How to Calculate the Sum and Average of Array Elements in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 01:14:02819browse

How to Calculate the Sum and Average of Array Elements in JavaScript?

Computing Sum and Average of Array Elements

To calculate the sum and average of elements in an array, you can use a for loop or a more efficient method using array methods.

Using a For Loop:

let sum = 0;
for (i = 0; i < elmt.length; i++) {
  sum += parseFloat(elmt[i]);
}
let average = sum / elmt.length;

Using Array Methods:

let sum = elmt.reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
let average = sum / elmt.length;

Here's the corrected code with the implemented calculations:

var i;
var elmt = new Array();

elmt[0] = "0";
elmt[1] = "1";
elmt[2] = "2";
elmt[3] = "3";
elmt[4] = "4";
elmt[5] = "7";
elmt[6] = "8";
elmt[7] = "9";
elmt[8] = "10";
elmt[9] = "11";

// Calculate sum using for loop
let sum = 0;
for (i = 0; i < elmt.length; i++) {
  sum += parseFloat(elmt[i]);
}

// Calculate average using array method
let average = sum / elmt.length;

// Display results
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + average + "<br/>");

The above is the detailed content of How to Calculate the Sum and Average of Array Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn