Java Reference
In-Depth Information
"the", "lazy",
"dog"]
Now we can use the reduce() function to calculage the total number of letters in the
sentence:
total = words.reduce( function(prev,word) {
return prev + word.length;
},0);
<< 36
average = total/words.length;
<< 4
Using map() and reduce() Together
The map() and reduce() methods are often used in combination to create some power-
ful transformations of data stored in arrays. Because the map() function returns the trans-
formed array, the reduce() can be chained on the end. For example, we can calculate the
sum of square numbers using the map() method to square each number in the array and
then use the reduce() method to add the results together:
[1,2,3].map(square).reduce( function(total,x) { return x +
total; });
<< 14
Another more complex example could be used to take an array of orders, apply a sales tax
to them using map() and then use reduce() to find the total:
var sales = [ 100, 230, 55];
totalAfterTaxSales = sales.map( function(amount) {
return amount * 1.15; // add 15% sales tax
}).reduce( function(prev,current){
return prev + current;
});
<< 442.75
Search WWH ::




Custom Search