Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created July 28, 2011 09:29
Show Gist options
  • Save JamieMason/1111276 to your computer and use it in GitHub Desktop.
Save JamieMason/1111276 to your computer and use it in GitHub Desktop.
Using underscore.js, return the average value from an array of Numbers.
function average (arr)
{
return _.reduce(arr, function(memo, num)
{
return memo + num;
}, 0) / arr.length;
}
@williamli
Copy link

@lfamorim
Copy link

@linus-amg
Copy link

@linus-amg
Copy link

linus-amg commented Jan 29, 2017

_.reduce(
  prices,
  (memo, num) => memo + num,
  0
) / prices.length || 1

@linus-amg
Copy link

linus-amg commented Jan 29, 2017

or without underscore/lodash

prices.reduce(
  (memo, num) => memo + num,
  0
) / prices.length || 1

or as a one-liner

prices.reduce((memo, num) => memo + num, 0) / prices.length || 1

or as a prototype of array

Array.prototype.avg = function () { return this.reduce((memo, num) => memo + num, 0) / this.length || 1 };

// and then doing prices.avg() which returns the result

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