Last active
November 2, 2018 17:32
-
-
Save facelordgists/44a05c181369f5eed31d3d702dd48bea to your computer and use it in GitHub Desktop.
JS: How to find the sum of an array of numbers using reduce() function.js #javascript #js #reduce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ----------------------------------- | |
// Method #1 | |
var sum = [1, 2, 3].reduce(add, 0); | |
function add(a, b) { | |
return a + b; | |
} | |
console.log(sum); // 6 | |
// ----------------------------------- | |
// Method #2 | |
// ECMAScript 2015 (aka ECMAScript 6) | |
var sum = [1, 2, 3].reduce((a, b) => a + b, 0); | |
console.log(sum); // 6 | |
// ----------------------------------- | |
// Method #3 | |
// Vanilla JS - slightly different syntactical approach | |
// Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values. | |
[1,2,3].reduce(function(acc, val) { return acc + val; }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment