How to find the sum of all elements of a given array in JavaScript ?
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:
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.
Javascript
let arr = [4, 8, 7, 13, 12]
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log( "Sum is " + sum)
|
We are going to use the Javascript forEach() method of the array to calculate the sum.
Example: This example shows the above-explained approach.
Javascript
let arr = [4, 8, 7, 13, 12]
let sum = 0;
arr.forEach(x => {
sum += x;
});
console.log( "Sum is " + sum);
|
We are going to use the Javascript reduce() method to find the sum of the array.
Example: This example shows the above-explained approach.
Javascript
let arr = [4, 8, 7, 13, 12]
let sum = arr.reduce( function (x, y) {
return x + y;
}, 0);
console.log( "Sum using Reduce method: " + sum);
|
Output
Sum using Reduce method: 44
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.
Javascript
let arr = [4, 8, 7, 13, 12];
function sumArray(arr, index) {
if (index === arr.length) {
return 0;
}
return arr[index] + sumArray(arr, index + 1);
}
console.log( "Sum is " + sumArray(arr, 0));
|
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.
Javascript
const _ = require( "lodash" );
let gfg = _.sum([5, 10, 15, 20, 25]);
console.log(gfg);
|
Output:
75
Last Updated :
07 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...