Skip to content

Instantly share code, notes, and snippets.

@boogie
Created January 22, 2019 04:35
Show Gist options
  • Save boogie/4c01c29513e2f08515093c446f2da474 to your computer and use it in GitHub Desktop.
Save boogie/4c01c29513e2f08515093c446f2da474 to your computer and use it in GitHub Desktop.
Calculating an array's sum and average
const numbers = [1, 4, 3, 5, 4];
// sum with reduce and first value
numbers.reduce((sum, value) => sum + value, 0); // 17
// sum with reduce, but missing first value
numbers.reduce((sum, value) => sum + value); // 17
// average with reduce, using extra function params
numbers.reduce((average, value, index, array) => average + value / array.length, 0); // 3.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment