
Find the average of all numbers in a given array
Let's say we wanted to write a function that calculates the average of all grades (including yours). We can do this in many different ways in JavaScript, but in this demo I will be showing you how to find the average using Higher-Order Functions and the "for" loop.
forEach loop
The forEach() method executes a provided function once for each array element.
constyourGrade=88;letclassGrades=[87,68,94,100,83,78,85,91,76,87];// push `yourGrade` to the end of classGradesclassGrades.push(yourGrade);console.log(classGrades);functionaverage(array){// initialize value of `sum`letsum=0;// capture the length of the arrayletarrayLength=array.length;// loop through the array via forEacharray.forEach((grade)=>{return(sum+=grade);});// formula to calculate average: sum / arrayLengthreturnMath.round(sum/arrayLength);}constavg=average(classGrades);console.log(avg);
for loop
Thefor()
loop iterates a specified amount of times, and does "something" that many times.
constyourGrade=88;letclassGrades=[87,68,94,100,83,78,85,91,76,87];console.log(classGrades);functionaverage(array){// initialize value of `sum`letsum=0;// capture the length of the arrayletarrayLength=array.length;// iterate over the arrayfor(leti=0;i<array.length;i++){// add each element to the `sum`sum+=array[i];}// formula to calculate average: sum / arrayLength/* since we are not pushing our grade to the array using `array.push()`, we need to do a little bit of algebra to add ourselves to the list */returnMath.round((sum+yourGrade)/(arrayLength+1));}constavg=average(classGrades);console.log(avg);
reduce
Thereduce()
method is quite similar to theforEach()
method, but requires a lot less coding. :)
constyourGrade=88;letclassGrades=[87,68,94,100,83,78,85,91,76,87];// push `yourGrade` to the end of classGradesclassGrades.push(yourGrade);console.log(classGrades);functionaverage(array){// action to do for every valueconstavg=array.reduce((previousValue,currentValue)=>previousValue+currentValue)/array.length;returnMath.round(avg);}constavg=average(classGrades);console.log(avg);
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse