Java Reference
In-Depth Information
reduce()
The reduce() method is another method that iterates over each value in the array, but
this time it cumulatively combines each result to return just a single value. The callback
function is used to describe how to combine each value of the array with the running total.
This is often used to calculate statistics such as averages based on data returned from a
database in array form. It usually takes two parameters: The first parameter represents the
previous value and the second parameter represents the current item in the array. The fol-
lowing example shows how to sum an array of numbers:
[1,2,3,4,5].reduce( function(prev,current){
return prev + current;
});
<< 15
The value of prev starts as the first item in the array. The value of prev then becomes the
result of this operation. Then the next item in the array is added to this running total, and
so on, until every item in the array has been added.
The reduce() method also takes a second parameter after the callback, which is the inital
value of prev . For example, we could total the numbers in an array, but starting at 10 ,
instead of zero:
[1,2,3,4,5].reduce( function(prev,current){
return prev + current;
},10); // <---- second parameter of 10 here
<< 25
Another example could be to calculate the average word length in a sentence:
sentence = "The quick brown fox jumped over the lazy dog"
<< "The quick brown fox jumped over the lazy dog"
The sentence can be converted into an array using the split() method:
words = sentence.split(" ");
<< ["The", "quick", "brown", "fox", "jumped", "over",
Search WWH ::




Custom Search