To get the average of an array in JavaScript, we can use the JavaScript Array reduce() method along with the length property. Here is the setup for how this can be done:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function sumArray(total, item) {
return total + item;
}
var averageOfNumbers = numbers.reduce(sumArray)/numbers.length;
console.log(averageOfNumbers);
#Output
5
The first part of the code above is just finding the sum of the array.
We then find the length of the array and divide the sum of the array by its length to get the average of the array.
We can also use a for loop to help get the sum of an array.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var total = 0;
for( var i =0; i<numbers.length; i++ ){
total += numbers[i];
}
var averageOfArray = total/numbers.length;
console.log(averageOfArray);
#Output
5
When working with collections of data in JavaScript, the ability to summarize the data easily is valuable.
One such case is if you want to get the average of an array of numbers.
To calculate the average of an array of numbers in JavaScript, the easiest way is with the reduce() method along with the length property.
Below again we show you how to get the average of an array of numbers in JavaScript.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function sumArray(total, item) {
return total + item;
}
var averageOfNumbers = numbers.reduce(sumArray)/numbers.length;
console.log(averageOfNumbers);
We can put our code in a function and shorten it so that we have a function that will return the average of any array passed to it.
function averageOfArray(arr){
return arr.reduce((a, b) => a + b) / arr.length;
};
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(averageOfArray(numbers));
#Output
5
Using a For Loop to Get the Average of an Array in JavaScript
Another way you can get the average of an array of numbers is with a for loop.
First, we need to initialize a variable that will keep the running sum and then add each element to the running sum.
The we simply divide the sum of the array by the length of the array.
Below shows you how to get the average of an array of numbers in JavaScript with a for loop.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var total = 0;
for( var i =0; i<numbers.length; i++ ){
total += numbers[i];
}
var averageOfArray = total/numbers.length;
We can put our code in a function to reuse the function to get the average of an array.
function averageOfArray(arr){
var total = 0;
for( var i =0; i<numbers.length; i++ ){
total += numbers[i];
}
return total/arr.length;
};
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(averageOfArray(numbers));
#Output
5
Hopefully this article has been useful for you to learn how to use JavaScript to get the average of an array.
Leave a Reply