Created
July 28, 2011 09:29
-
-
Save JamieMason/1111276 to your computer and use it in GitHub Desktop.
Using underscore.js, return the average value from an array of Numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function average (arr) | |
{ | |
return _.reduce(arr, function(memo, num) | |
{ | |
return memo + num; | |
}, 0) / arr.length; | |
} |
@klarstrup LOL
@klarstrup LOL
@klarstrup LOL
_.reduce(
prices,
(memo, num) => memo + num,
0
) / prices.length || 1
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
@Luks1: It's 2.75