Reputation: 6625
anyone got any examples on how to use the reduce method in underscore.
Upvotes: 2
Views: 14869
Reputation: 3542
They have it... http://underscorejs.org/#reduce Right there - at the official Underscore.js site.
Upvotes: 4
Reputation: 104770
Here are two javascript examples, quite similar to underscore.
These find the mathematical mean and the standard deviation in an array of numbers.
You often see reduce working with thousands or millions of items in arrays related to populatons or statistics.
Math.mean= function(array){
return array.reduce(function(a, b){return a+b;})/array.length;
}
Math.stDeviation= function(array){
var mean= Math.mean(array),
dev= array.map(function(itm){return (itm-mean)*(itm-mean);});
return Math.sqrt(dev.reduce(function(a, b){return a+b;})/array.length);
}
var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))
/* returned value: (String)
mean: 6.0625; deviation: 0.899913190257816
*/
Upvotes: 19