Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created July 28, 2011 09:29
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
}
@loujaybee
Copy link

Hey Jamie, it doesn't work for 0 length arrays. So a slight amendment! :)

     return _.reduce(arr, function(memo, num) {
        return memo + num;
    }, 0) / (arr.length === 0 ? 1 : arr.length);

@timcharper
Copy link

Infinity and 0 are both wrong for the average of nothing, although Infinity is probably less wrong. Throwing an exception or using an option monad is a better approach.

@Luks1
Copy link

Luks1 commented Apr 1, 2016

['3.00', '3.50', '3.33', '2.90']
i need an average of this array please

@klarstrup
Copy link

@Luks1: It's 2.75

@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