Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to find the sum of an array of numbers in Javascript ?

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

I thought $.each might be useful, but I'm not sure how to implement it.
by

2 Answers

aashaykumar

console.log(
[1, 2, 3, 4].reduce((a, b) => a + b, 0)
)
console.log(
[].reduce((a, b) => a + b, 0)
)
kshitijrana14
Why not reduce? It's usually a bit counter intuitive, but using it to find a sum is pretty straightforward:
var a = [1,2,3];
var sum = a.reduce(function(a, b) { return a + b; }, 0);

Login / Signup to Answer the Question.