[javascript] How to compute the sum and average of elements in an array?

Start by defining all of the variables we plan on using. You'll note that for the numbers array, I'm using the literal notation of [] as opposed to the constructor method array(). Additionally, I'm using a shorter method to set multiple variables to 0.

var numbers = [], count = sum = avg = 0;

Next I'm populating my empty numbers array with the values 0 through 11. This is to get me to your original starting point. Note how I'm pushing onto the array count++. This pushing the current value of count, and then increments it for the next time around.

while ( count < 12 )
    numbers.push( count++ );

Lastly, I'm performing a function "for each" of the numbers in the numbers array. This function will handle one number at a time, which I'm identifying as "n" within the function body.

numbers.forEach(function(n){
  sum += n; 
  avg = sum / numbers.length;
});

In the end, we can output both the sum value, and the avg value to our console in order to see the result:

// Sum: 66, Avg: 5.5
console.log( 'Sum: ' + sum + ', Avg: ' + avg );

See it in action online at http://jsbin.com/unukoj/3/edit

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to average

np.mean() vs np.average() in Python NumPy? Take a list of numbers and return the average How to manipulate arrays. Find the average. Beginner Java Finding moving average from data points in Python Calculating average of an array list? SQL query with avg and group by How to compute the sum and average of elements in an array? Finding the average of a list Trying to get the average of a count resultset Calculating arithmetic mean (one type of average) in Python