Calculate sum of all array values in JavaScript
This post will discuss how to calculate the sum of all the values in an array in JavaScript.
1. Using Array.reduce() function
The Array.reduce() function in Java is used to call a reducing function on each array element, and accumulating the results in a single value. We can calculate the sum of all array values by using a reducer function that adds the current element’s value to the already computed sum of the previous values. This is demonstrated below using an anonymous function:
|
1 2 3 4 5 6 7 8 |
add = function(arr) { return arr.reduce((a, b) => a + b, 0); }; let arr = [3, 2, 1, 8, 6]; let sum = add(arr); console.log(sum); // 20 |
2. Using Lodash Library
Another alternative to find the sum of all values in an array is using the _.sum function from the lodash library. This function takes an array of numbers as an argument and returns the sum of all the elements present in the array. The following code example demonstrates its usage:
|
1 2 3 4 5 6 7 |
// import lodash library let _ = require('lodash'); let arr = [3, 2, 1, 8, 6]; let sum = _.sum(arr); console.log(sum); // 20 |
3. Using a loop
A naive solution is to use a loop for iterating over the array elements and keeping track of the sum in a variable. The variable is updated with the current element’s value in each iteration of the loop. The loop can be either a for loop, an enhanced for loop, or forEach() function. The following code demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
let arr = [3, 2, 1, 8, 6]; // 1. Using a for loop let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } console.log(sum); // 20 // 2. Using a for…of loop sum = 0; for (let i of arr) { sum += i; } console.log(sum); // 20 // 3. Using a forEach function that takes a callback function sum = 0; arr.forEach(function (value) { sum += value; }); console.log(sum); // 20 |
That’s all about calculating the sum of all values in an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)