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.
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.
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? :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With