My Development Notes

Programming Made Easier


Sum of elements in an array in JavaScript

This is how the sum of elements in an array should look like:

// [44,4,3] = 51 (i.e., 44+4+3)
// [2,3,7,8] = 20

We can use the reduce() method to find the sum of elements in an array :

function sumEl(arr) {
return arr.reduce((acc, curr) => acc + curr);
}

console.log(sumEl([2,4,6]));
// returns 12 to the console

Here, the reduce() method actually takes two parameters, the first one we can call accumulator, and the second one, current. So, here in the above example, we’ve added acc and curr in a recursive or repetitive manner as such:

sumEl([2,4,6]);

// 2 + 4 (which is 6) then 6 + 6 (which is 12, and so on..)

You can also write the code this way:

let arr = [ 7, 88, 9, 1];
let sumOf = arr.reduce(function(a, b) {
return a + b;
},0)

sumOf; 
// returns 105

Here, the reduce method works the same as the first example. Also, note that ‘0’ at the end of code is the initial value. Not clear yet? Let’s tweak Example 2 a little bit so that you get a clearer picture :

let arr = [ 7, 88, 9, 1];

sumOf = 0;   // created a variable 'sumOf' and initialized at '0'

let sumOf = arr.reduce(function(a, b) {
return a + b;
})

sumOf; 
// returns 105

Posted

in

by

Tags:

Leave a Reply