Sometimes, we want to compute the sum or average of the elements in a JavaScript array.
In this article, we’ll look at how to compute the sum and average of the elements in a JavaScript array.
Use a Loop
We can use the for-of loop to loop through an array to add all the numbers together to compute the sum.
Then to compute the average, we can divide the sum by the array’s length.
For instance, we can write:
const arr = [1, 2, 3]
let sum = 0;
for (const a of arr) {
sum += a;
}
const avg = sum / arr.length;
console.log(sum)
console.log(avg)
We define an arr
array with some numbers in it.
Then we define the sum
variable and initialize it to 0.
Next, we add the for-of loop to loop through the arr
entries.
a
has the arr
entry that’s being looped through.
In the loop body, we add the a
value to the sum
.
Then we create the avg
variable and assign the quotient of the sum
and arr.length
to it.
Therefore, sum
is 6 and avg
is 2.
Use the Array.prototype.reduce Method
We can also use the array reduce
instance method to compute the sum.
Then we can compute the average the same way as the previous example.
For instance, we can write:
const arr = [1, 2, 3]
const sum = arr.reduce((partialSum, a) => partialSum + a, 0)
const avg = sum / arr.length;
console.log(sum)
console.log(avg)
The reduce
method takes a callback that has the partialSum
and a
.
Where partialSum
is the partial sum returned after adding the arr
entries that are iterated through.
a
is the entry of arr
being iterated through.
The callback returns the new partial sum.
The 2nd argument is the initial value of the sum
.
The rest of the code is the same and we get the same result as the previous example.
Lodash sum and mean Methods
Lodash has the sum
method that returns the sum of an array entries.
The mean
method returns the average of the array entries.
For instance, we can write:
const arr = [1, 2, 3]
const sum = _.sum(arr)
const avg = _.mean(arr)
console.log(sum)
console.log(avg)
Both methods take the array we want to do the computation with as the argument.
Then we get the same result as before.
Conclusion
We can use Lodash or plain JavaScript to compute the sum and average of array entries.