In this article, we will learn how we can find the sum of all elements/numbers of the given array. we will have an array and we need to print the sum of all of its elements.
Below all the approaches are described with a proper example:
Table of Content
Method 1: Using for loop
We are simply going to iterate over all the elements of the array using a Javascript for loop to find the sum.
Example: This example shows the above-explained approach.
// Creating array let arr = [4, 8, 7, 13, 12] // Creating variable to store the sum let sum = 0; // Running the for loop for (let i = 0; i < arr.length; i++) {
sum += arr[i];
} console.log( "Sum is " + sum) // Prints: 44
|
Sum is 44
Method 2: Using forEach() Method
We are going to use the Javascript forEach() method of the array to calculate the sum.
Example: This example shows the above-explained approach.
// Creating array let arr = [4, 8, 7, 13, 12] // Creating variable to store the sum let sum = 0; // Calculation the sum using forEach arr.forEach(x => { sum += x;
}); // Prints: 44 console.log( "Sum is " + sum);
|
Sum is 44
Method 3: Using reduce() Method
We are going to use the Javascript reduce() method to find the sum of the array.
Example: This example shows the above-explained approach.
// Creating array let arr = [4, 8, 7, 13, 12] // Using reduce function to find the sum let sum = arr.reduce( function (x, y) {
return x + y;
}, 0); // Prints: 44 console.log( "Sum using Reduce method: " + sum);
|
Sum using Reduce method: 44
Method 4: Using Recursion
We could define recursion formally in simple words, that is, a function calling itself again and again until it doesn’t have left with it anymore.
Example: This example shows the above-explained approach.
// Creating array let arr = [4, 8, 7, 13, 12]; // Function to find the sum of the array using recursion function sumArray(arr, index) {
if (index === arr.length) {
return 0;
}
return arr[index] + sumArray(arr, index + 1);
} console.log( "Sum is " + sumArray(arr, 0));
|
Sum is 44
Method 5: Using Lodash _.sum() Method
In this approach, we are using the Lodash _.sum() method for getting the sum of all element of an array.
Example: This example shows the implementation of the above-explained appraoch.
// Requiring the lodash library const _ = require( "lodash" );
// Use of _.sum () method let gfg = _.sum([5, 10, 15, 20, 25]); // Printing the output console.log(gfg); |
Output:
75