Q:

js sum of array

const sum = arr => arr.reduce((a, b) => a + b, 0);
8
arrSum = function(arr){  return arr.reduce(function(a,b){    return a + b  }, 0);}
1
[1, 2, 3, 4].reduce((a, b) => a + b, 0)

// Output: 10
3
const arrSum = arr => arr.reduce((a,b) => a + b, 0)
8
function getArraySum(a){
    var total=0;
    for(var i in a) { 
        total += a[i];
    }
    return total;
}

var payChecks = [123,155,134, 205, 105]; 
var weeklyPay= getArraySum(payChecks); //sums up to 722
5
arr.reduce((a, b) => a + b)
3
const sum = array.reduce((accumulator, element) => {
  return accumulator + element;
}, 0);
// An example that will loop through an array adding
// each element to an accumulator and returning it
// The 0 at the end initializes accumulator to start at 0
// If array is [2, 4, 6], the returned value in sum
// will be 12 (0 + 2 + 4 + 6)

const product = array.reduce((accumulator, element) => {
  return accumulator * element;
}, 1);
// Multiply all elements in array and return the total
// Initialize accumulator to start at 1
// If array is [2, 4, 6], the returned value in product
// will be 48 (1 * 2 * 4 * 6)
5
const summation = (n) => (n * (n + 1)) / 2;
1
console.log(
  [1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
  [].reduce((a, b) => a + b, 0)
)
4

New to Communities?

Join the community