Skip to content

Instantly share code, notes, and snippets.

@meetbryce
Last active May 12, 2019 19:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meetbryce/87f4314a4622428f5bf3 to your computer and use it in GitHub Desktop.
Save meetbryce/87f4314a4622428f5bf3 to your computer and use it in GitHub Desktop.
Average or Sum the values in an array using Javascript (and Underscore.js)
// requires Underscore.js
// uses jQuery style funciton declaration (if you aren't using jQuery, simply re-arrange the declaration)
function sum(arr) {
// returns the sum total of all values in the array
return _.reduce(arr, function(memo, num) { return memo + num}, 0);
}
function average(arr) {
// returns the average of all values in the array
return sum(arr) / arr.length;
}
@johbochy
Copy link

this is cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment