How to calculate the sum and average value of elements in an array?

I have problems with adding all elements of the array and their averaging. How would I do this and implement it using the code that I currently have? Elements should be defined, as I have below.

<script type="text/javascript"> //<![CDATA[ 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"; // Problem here for (i = 9; i < 10; i++){ document.write("The sum of all the elements is: " + /* Problem here */ + " The average of all the elements is: " + /* Problem here */ + "<br/>"); } //]]> </script> 
+148
javascript arrays average
Apr 28 2018-12-12T00:
source share
33 answers
  • one
  • 2
 var sum = 0; for( var i = 0; i < elmt.length; i++ ){ sum += parseInt( elmt[i], 10 ); //don't forget to add the base } var avg = sum/elmt.length; document.write( "The sum of all the elements is: " + sum + " The average is: " + avg ); 

Just iterate over the array, since your values ​​are strings, they must first be converted to integers. And the average value is simply the sum of the values ​​divided by the number of values.

+121
Apr 28 2018-12-12T00:
source share

The solution that I find more elegant:

 var sum, avg = 0; // dividing by 0 will return Infinity // arr must contain at least 1 element to use reduce if (arr.length) { sum = arr.reduce(function(a, b) { return a + b; }); avg = sum / arr.length; } document.write("The sum is: " + sum + ". The average is: " + avg + "<br/>"); 
+444
May 16 '12 at 18:12
source share

ES6

 const average = arr => arr.reduce( ( p, c ) => p + c, 0 ) / arr.length; const result = average( [ 4, 4, 5, 6, 6 ] ); // 5 console.log(result); 
+93
Aug. 14 '13 at 14:32
source share

Calculation of average (average) using reduction and ES6:

 const average = list => list.reduce((prev, curr) => prev + curr) / list.length; const list = [0, 10, 20, 30] average(list) // 15 
+25
Aug 08 '18 at 15:55
source share

usually the average value using decreasing one row is as follows

 elements.reduce(function(sum, a,i,ar) { sum += a; return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0); 

in particular the question asked

 elements.reduce(function(sum, a,i,ar) { sum += parseFloat(a); return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0); 

effective version is similar to

 elements.reduce(function(sum, a) { return sum + a },0)/(elements.length||1); 

Understand Javascript Array Decrease by 1 minute http://www.airpair.com/javascript/javascript-array-reduce

as gotofritz pointed out, it seems that Array.reduce is missing undefined values. so here is the fix:

 (function average(arr){var finalstate=arr.reduce(function(state,a) { state.sum+=a;state.count+=1; return state },{sum:0,count:0}); return finalstate.sum/finalstate.count})([2,,,6]) 
+20
May 23 '14 at 7:46
source share

Suppose we have an array of numbers like this:

 var values = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; 

The average value is obtained by the following formula

A = (1 / n) Σxi (from i = 1 to n) ... So: x1 / n + x2 / n + ... + xn / n

We divide the current value by the number of values ​​and add the previous result to the return value.

Signature Reduction Method

 reduce(callback[,default_previous_value]) 

The callback function reduces the following parameters:

  • p : Result of previous calculation
  • c : current value (from current index)
  • i : current array element index value
  • a : current reduced array

The second reduction parameter is the default value ... (used if the array is empty ).

Thus, the average reduction method will be:

 var avg = values.reduce(function(p,c,i,a){return p + (c/a.length)},0); 

If you prefer, you can create a separate function

 function average(p,c,i,a){return p + (c/a.length)}; function sum(p,c){return p + c)}; 

And then just refer to the callback method signature

 var avg = values.reduce(average,0); var sum= values.reduce(sum,0); 

Or skip the prototype array directly.

 Array.prototype.sum = Array.prototype.sum || function (){ return this.reduce(function(p,c){return p+c},0); }; 

You can split the value each time you call the reduction method.

 Array.prototype.avg = Array.prototype.avg || function () { return this.reduce(function(p,c,i,a){return p+(c/a.length)},0); }; 

Or even better , using the previously defined Array.protoype.sum ()

optimize the process causing division only once :)

 Array.prototype.avg = Array.prototype.avg || function () { return this.sum()/this.length; }; 

Then to any object of the array area:

 [2, 6].avg();// -> 4 [2, 6].sum();// -> 8 

NB: an empty array with the return of the NaN wish is rather 0 in my point of view and can be useful in specific cases of use.

+14
Mar 15 '16 at 10:22
source share

You can also use lodash , _.sum (array) and _.mean (array) in the Math part (there are other convenient things too).

 _.sum([4, 2, 8, 6]); // => 20 _.mean([4, 2, 8, 6]); // => 5 
+12
Oct 07 '17 at 12:08 on
source share

Not the fastest, but the shortest and in one line uses map () and reduce ():

 var average = [7,14,21].map(function(x,i,arr){return x/arr.length}).reduce(function(a,b){return a + b}) 
+6
Apr 12 '14 at 17:01
source share

I use these methods in my personal library:

 Array.prototype.sum = Array.prototype.sum || function() { return this.reduce(function(sum, a) { return sum + Number(a) }, 0); } Array.prototype.average = Array.prototype.average || function() { return this.sum() / (this.length || 1); } 

EDIT: To use them, simply specify an array for its sum or average value, for example:

 [1,2,3].sum() // = 6 [1,2,3].average() // = 2 
+5
Feb 23 '15 at 2:54
source share

In ES6 ready-made browsers, this polyfill can be useful.

 Math.sum = (...a) => Array.prototype.reduce.call(a,(a,b) => a+b) Math.avg = (...a) => this.sum(...a)/a.length; 

You can use the same calling method between Math.sum , Math.avg and Math.max , for example:

 var maxOne = Math.max(1,2,3,4) // 4; 

You can use Math.sum as

 var sumNum = Math.sum(1,2,3,4) // 10 

or if you have an array to summarize, you can use

 var sumNum = Math.sum.apply(null,[1,2,3,4]) // 10 

as

 var maxOne = Math.max.apply(null,[1,2,3,4]) // 4 
+5
Nov 18 '16 at 15:56
source share

One sneaky way you could do this, though it does require the use of the (highly hated) eval ().

 var sum = eval(elmt.join('+')), avg = sum / elmt.length; document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>"); 

Just thought I would post this as one of these out-of-the-box options. You never know, cunning can give you (or take away) a point.

+4
Jan 03 '13 at 16:06
source share

Here is a quick addition to the "Math" object in javascript to add the "middle" command to it !!

 Math.average = function(input) { this.output = 0; for (this.i = 0; this.i < input.length; this.i++) { this.output+=Number(input[this.i]); } return this.output/input.length; } 

Then I have this add-on to the Math object to get the sum!

 Math.sum = function(input) { this.output = 0; for (this.i = 0; this.i < input.length; this.i++) { this.output+=Number(input[this.i]); } return this.output; } 

So all you do is

 alert(Math.sum([5,5,5])); //alerts "15" alert(Math.average([10,0,5])); //alerts "5" 

And where I put the placeholder array, just pass your variable (input, if they are numbers, can be a string because it is parsed into a number!)

+3
Apr 16 '18 at 20:27
source share

set your loop counter to 0 .... you get element 9, and then you finish what you have now. Other answers are basic math. Use a variable to store your sum (you must pass the lines to int) and divide it by the length of the array.

+1
Apr 28 2018-12-12T00:
source share

Start by defining all the variables that we plan to use. You will notice that for the numbers array I use the literal notation [] , unlike the constructor method array() . In addition, I use a shorter method to set multiple variables to 0.

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

Next, I fill my empty array of numbers with values ​​from 0 to 11. This should lead me to the starting point. Notice how I click on the count++ array. This results in the current value of the counter, and then increments it the next time.

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

Finally, I perform the function “for each” of numbers in an array of numbers. This function will process one number at a time, which I define as "n" inside the body of the function.

 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 to see the result:

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

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

+1
Apr 28 2018-12-12T00:
source share

I will simply describe the answer of Abdennour TOUMI. that's why:

1.) I agree with Brad, I do not think it is a good idea to extend an object that we did not create.

2.) array.length absolutely reliable in javascript, I prefer Array.reduce beacuse a=[1,3];a[1000]=5; , now a.length will return 1001 .

 function getAverage(arry){ // check if array if(!(Object.prototype.toString.call(arry) === '[object Array]')){ return 0; } var sum = 0, count = 0; sum = arry.reduce(function(previousValue, currentValue, index, array) { if(isFinite(currentValue)){ count++; return previousValue+ parseFloat(currentValue); } return previousValue; }, sum); return count ? sum / count : 0; }; 
+1
Jan 15 '15 at 5:46
source share

In evergreen browsers, you can use the arrow functions avg = [1,2,3].reduce((a,b) => (a+b);

Performing it 100,000 times, the time difference between approaching and shortening the cycle for the cycle is negligible.

 s=Date.now();for(i=0;i<100000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) / n.length }; console.log("100k reduce took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<100000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a/nl }; console.log("100k for loop took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<1000000;i++){n=[1,2,3]; nl=n.length; a=0; for(j=nl-1;j>0;j--){a=a+n[j];} a/nl }; console.log("1M for loop took " + (Date.now()-s) + "ms."); s=Date.now();for(i=0;i<1000000;i++){ n=[1,2,3]; a=n.reduce((a,b) => (a+b)) / n.length }; console.log("1M reduce took " + (Date.now()-s) + "ms."); /* * RESULT on Chrome 51 * 100k reduce took 26ms. * 100k for loop took 35ms. * 10M for loop took 126ms. * 10M reduce took 209ms. */ 
+1
Sep 29 '16 at 17:13
source share

Just for kicks:

 var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0; for (; ++i < l; sum += elmt[i]) ; document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l))); 
0
Oct 07 '13 at 16:18
source share

Here is a small little solution for a medium array that is very inefficient but has very specific applications:

 var average = elmt.reduce(function(x,y,z){ return ((x * z) + y) / (z + 1); }); 

Documents for the reduce method

0
Jan 12 '15 at 5:02
source share
 Array.prototype.avg=function(fn){ fn =fn || function(e,i){return e}; return (this.map(fn).reduce(function(a,b){return parseFloat(a)+parseFloat(b)},0) / this.length ) ; }; 

Then:

 [ 1 , 2 , 3].avg() ; //-> OUT : 2 [{age:25},{age:26},{age:27}].avg(function(e){return e.age}); // OUT : 26 
0
Dec 16 '15 at 15:54
source share
 protected void Submit_Click(object sender, EventArgs e) { foreach (ComputerLabReservationList row in db.ComputerLabReservationLists) { if (row.LabNo == lblLabNo.Text && row.ReservationDate == StartCld.Text && row.StartEndTime == ddlstartendtime.Text) { // string display = "This time have been reserved by others. Please reserve again."; // ClientScript.RegisterStartupScript(this.GetType(), "yourMessage", "alert('" + display + "');", true); ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('This time already booked by other. Please insert another time');window.location ='Computerlabs.aspx';", true); } else { ComputerLabReservationList crl = new ComputerLabReservationList() { ResvId = lblreservationid.Text, LabNo = lblLabNo.Text, LecturerId = lblLecturerID.Text, ReservationDate = StartCld.Text, StartEndTime = ddlstartendtime.Text }; db.ComputerLabReservationLists.InsertOnSubmit(crl); db.SubmitChanges(); ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Your Reservation was sucessfully');window.location ='MyComputerReservation.aspx';", true); } } } 
0
Dec 17 '15 at 3:23
source share

I think we can do as

 var k=elmt.reduce(function(a,b){return parseFloat(a+parseFloat(b));}) var avg=k/elmt.length; console.log(avg); 

I use parseFloat twice, because when 1) you add (a) 9 + b ("1"), then the result will be "91", but we want to add. so i used parseFloat

2) When the addition of (a) 9 + parseFloat ("1") occurs, the result will be "10", but it will be on the line that we do not want to use again parseFloat.

I hope I get it. Suggestions are welcome

0
Mar 15 '16 at 11:01
source share

Here is my newbie way to just find avg. Hope this helps someone.

 function numAvg(num){ var total = 0; for(var i = 0;i < num.length; i++) { total+=num[i]; } return total/num.length; } 
0
May 29 '16 at 18:55
source share

here is your one liner:

 var average = arr.reduce((sum,item,index,arr)=>index !== arr.length-1?sum+item:sum+item/arr.length,0) 
0
Jan 04 '17 at 19:51
source share

I think this may be a direct solution to calculate the average with a for loop and function.

 var elmts = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; function average(arr) { var total = 0; for (var i = 0; i < arr.length; i++) { total += arr[i]; } console.log(Math.round(total/arr.length)); } average(elmts); 
0
Feb 02 '17 at 20:54 on
source share

There seems to be an infinite number of solutions for this, but I found it to be concise and elegant.

 const numbers = [1,2,3,4]; const count = numbers.length; const reducer = (adder, value) => (adder + value); const average = numbers.map(x => x/count).reduce(reducer); console.log(average); // 2.5 

Or more precisely:

 const numbers = [1,2,3,4]; const average = numbers.map(x => x/numbers.length).reduce((adder, value) => (adder + value)); console.log(average); // 2.5 

Depending on your browser, you may need to make explicit function calls, as arrow functions are not supported:

 const r = function (adder, value) { return adder + value; }; const m = function (x) { return x/count; }; const average = numbers.map(m).reduce(r); console.log(average); // 2.5 

Or:

 const average1 = numbers .map(function (x) { return x/count; }) .reduce(function (adder, value) { return adder + value; }); console.log(average1); 
0
Feb 25 '18 at 18:41
source share

If you need an average value and you can skip the requirement for calculating the sum, you can calculate the average value with a single call to the Reduce method:

 // Assumes an array with only values that can be parsed to a Float var reducer = function(cumulativeAverage, currentValue, currentIndex) { // 1. multiply average by currentIndex to find cumulative sum of previous elements // 2. add currentValue to get cumulative sum, including current element // 3. divide by total number of elements, including current element (zero-based index + 1) return (cumulativeAverage * currentIndex + parseFloat(currentValue))/(currentIndex + 1) } console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(reducer, 0)); // => 5.5 console.log([].reduce(reducer, 0)); // => 0 console.log([0].reduce(reducer, 0)); // => 0 console.log([].reduce(reducer, 0)); // => 0 console.log([,,,].reduce(reducer, 0)); // => 0 console.log([].reduce(reducer, 0)); // => 0 
0
Jul 08 '18 at 18:26
source share

If someone needs it - here is a recursive mean.

In the context of the original question, you can use a recursive average if you allowed the user to insert additional values ​​and, while not incurring the cost of visiting each element again, wanted to “update” the existing average.

 /** * Computes the recursive average of an indefinite set * @param {Iterable<number>} set iterable sequence to average * @param {number} initAvg initial average value * @param {number} initCount initial average count */ function average(set, initAvg, initCount) { if (!set || !set[Symbol.iterator]) throw Error("must pass an iterable sequence"); let avg = initAvg || 0; let avgCnt = initCount || 0; for (let x of set) { avgCnt += 1; avg = avg * ((avgCnt - 1) / avgCnt) + x / avgCnt; } return avg; // or {avg: avg, count: avgCnt}; } average([2, 4, 6]); //returns 4 average([4, 6], 2, 1); //returns 4 average([6], 3, 2); //returns 4 average({ *[Symbol.iterator]() { yield 2; yield 4; yield 6; } }); //returns 4 

How:

this works by maintaining the current average and number of elements. When you need to add a new value, you increment the counter by 1, scale the existing average value (count-1)/count and add newValue/count to the average.

Benefits:

  • You do not summarize all the elements, which can lead to a large number that cannot be stored in 64-bit floating point format.
  • You can “update” the existing average if additional values ​​become available.
  • You can perform a moving average without knowing the length of the sequence.

Disadvantages:

  • entails much more units
  • not infinite - limited by Number.MAX_SAFE_INTEGER elements if you are not using BigNumber
0
04 Oct '18 at 2:54 on
source share

Average HTML content itens

With jQuery or Javascript querySelector , you have a direct binding to formatted data ... Example:

 <p>Elements for an average: <span class="m">2</span>, <span class="m">4</span>, <span class="m">2</span>, <span class="m">3</span>. </p> 

So with jQuery you have

 var A = $('.m') .map(function(idx) { return parseInt($(this).html()) }) .get(); var AVG = A.reduce(function(a,b){return a+b}) / A5.length; 

See 4 more ways (!) To access them and average it: http://jsfiddle.net/4fLWB/

-one
Jul 19 '14 at
source share

var arr = [1,2,3,4,5]

 function avg(arr){ var sum = 0; for (var i = 0; i < arr.length; i++) { sum += parseFloat(arr[i]) } return sum / i; } 

avg (arr) ====== → 3

This works with strings as numbers or numbers in an array.

-one
Dec 15 '15 at 23:50
source share

A simple code might look like this:

 var sum = eval("parseInt(" + elmt.join(") + parseInt(") + ");"); var avg = sum / elmt.length; document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>"); 

If you need a summary of floating point numbers, use parseFloat instead of parseInt .

-2
Jan 16 '14 at 20:32
source share
  • one
  • 2



All Articles