Find the average of n numbers using JavaScript
Tutorial to write a JavaScript function to find the average of n numbers of items in an Array using JavaScript.
In this tutorial, we will learn how to find the average of the n<sup>th</sup> number of items in an array using JavaScript.
There is no built-in JavaScript function to find the average of numbers. However, we can just write a function knowing the mathematical formula of finding the average of a given set of numbers.
Mathematically,
average = (sum of all the values) / number of values
Let's say Jack received his report card and these are his marks:
| English | Math | Biology | Chemistry | Physics |
|---|---|---|---|---|
| 75 | 80 | 90 | 60 | 70 |
So the average of the marks will be:
average = (75 + 80 + 90 + 60 + 70) / 5 (five subjects) average = 75
So, now let us write a JavaScript function to automate the process of finding the average easily.
The JavaScript function will take the N numbers of values of an array and it will return the average of the values.
function findAvg(arr){ let sumOfElement = 0; let totalNumOfElement = arr.length; arr.forEach(element =>{ sumOfElement += element }) return average = sumOfElement/totalNumOfElement } console.log('Average:', findAvg([75,80,90,60,70]))
Output:
Average: 75
Here, in the above code:
arr.length : gives us the total number of items.
we have used forEach() to loop through each item in the array and added the sum to the variable sumOfElement .
In the end, we have divided the total sum of the items by the total number of items to get the average as the return value.
<u>Alternative Method:</u>
We can also use for loop to do the same task as above.
function findAvg(arr){ let sumOfElement = 0; let totalNumOfElement = arr.length; for(i=0; i < totalNumOfElement;i++) { sumOfElement += arr[i] } return average = sumOfElement/totalNumOfElement } console.log('Average:', findAvg([75,80,90,60,70])) // Average: 75
So, this is how you can pass N numbers of values as a parameter to the function to return the average in JavaScript.
Related Articles:
Related Posts
Best way - Split an array into half in Javascript
To divide an single array into half i.e into two different arrays without modifying the original array we can use Array.slice() method in JavaScript.
Merge Two Arrays and Remove Duplicates - JavaScript
Tutorial on how to merge two or more array and remove duplicates in JavaScript.
How to multiply all numbers in an array using JavaScript
Quick tutorial on how to multiply all the elements in an array using iterative i.e loop and reduce method in JavaScript.
Fill array with incrementing numbers/ intergers using JavaScript
Find out how to fill an array with incrementing numbers/integers using JavaScript's for loop and Array.from() method with keys().
