In this article, you will learn how to find the sum of an array of numbers in Javascript. There are various ways to find the sum of an array of numbers in Javascript. You can find the sum of an array of numbers using reduce()
method, loops(for
loop, forEach
loop) or lodash library. Let’s discuss each of them and try examples:
The reduce()
method executes a user-supplied “reducer” callback function on each element of the array, in order, pass in the return value from the calculation on the preceding element and it returns a single value.
let arr = [5, 10, 15, 20];
let sum = arr.reduce(function (a, b) {
return a + b;
}, 0); // with initial value to avoid when the array is empty
console.log(sum); // Output: 50
Note:
Even better! If you use ES2015, you can use reduce()
function like this:
const sum = [5, 10, 15, 20].reduce((a, b) => a + b,0); // with initial value to avoid when the array is empty
console.log(sum); // Output: 50
The for loop is used to iterate an array. You can use it to add all the numbers in an array and store it in a variable.
const array = [5, 10, 15, 20];
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.log(sum); // Output = 50
Another way of calculating the sum of an array of numbers is using a forEach
loop.
const array = [5, 10, 15, 20];
let sum = 0;
array.forEach(number => {
sum += number;
})
console.log(sum); // Output = 50
One another way of calculating the sum of an array of numbers using _.sum(array)
Include the Lodash Library in your code:
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
Calculating the sum of the values in the array.
const array = [5, 10, 15, 20];
let sum = _.sum(array);
console.log(sum); // Output = 50
I hope this article will help you to understand how to find the sum of an array of numbers in Javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments