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.
const yourGrade = 88; let classGrades = [ 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ]; // push `yourGrade` to the end of classGrades classGrades.push(yourGrade); console.log(classGrades); function average(array) { // initialize value of `sum` let sum = 0; // capture the length of the array let arrayLength = array.length; // loop through the array via forEach array.forEach((grade) => { return (sum += grade); }); // formula to calculate average: sum / arrayLength return Math.round(sum / arrayLength); } const avg = average(classGrades); console.log(avg);
for loop
The for()
loop iterates a specified amount of times, and does "something" that many times.
const yourGrade = 88; let classGrades = [ 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ]; console.log(classGrades); function average(array) { // initialize value of `sum` let sum = 0; // capture the length of the array let arrayLength = array.length; // iterate over the array for (let i = 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 */ return Math.round((sum + yourGrade) / (arrayLength + 1)); } const avg = average(classGrades); console.log(avg);
reduce
The reduce()
method is quite similar to the forEach()
method, but requires a lot less coding. :)
const yourGrade = 88; let classGrades = [ 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 ]; // push `yourGrade` to the end of classGrades classGrades.push(yourGrade); console.log(classGrades); function average(array) { // action to do for every value const avg = array.reduce((previousValue, currentValue) => previousValue + currentValue) / array.length; return Math.round(avg); } const avg = average(classGrades); console.log(avg);
Top comments (0)