Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save facelordgists/44a05c181369f5eed31d3d702dd48bea to your computer and use it in GitHub Desktop.
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
// -----------------------------------
// 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