Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the sum of an array of numbers

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.

like image 444
akano1 Avatar asked Aug 04 '09 22:08

akano1


People also ask

How do you sum numbers in JavaScript?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.


1 Answers

This'd be exactly the job for reduce.

If you're using ECMAScript 2015 (aka ECMAScript 6):

const sum = [1, 2, 3].reduce((partialSum, a) => partialSum + a, 0); console.log(sum); // 6

DEMO

For older JS:

const sum = [1, 2, 3].reduce(add, 0); // with initial value to avoid when the array is empty  function add(accumulator, a) {   return accumulator + a; }  console.log(sum); // 6

Isn't that pretty? :-)

like image 62
Florian Margaine Avatar answered Oct 15 '22 02:10

Florian Margaine