Java Reference
In-Depth Information
The
reduce()
method applies a reduction operation on the array, reducing it to a
single value such as computing the sum of all elements in a number array. It returns a
computed value. Its signature is:
reduce(callback, initialValue)
The first argument,
callback
, is a function that is called with four arguments: the
previous value, the current value, the current index, and the array itself.
If
initialValue
is unspecified:
For the first call to
•
callback
, the first element of the array is
passed as the previous value and the second element as the
current value; the index of the second element is passed as the
index
•
For subsequent calls to
callback
, the value returned from the
previous call is passed as the previous value. The current value
and index are the value and index of the current element
If
initialValue
is specified:
For the first call to
•
callback
,
initialValue
is passed as the
previous value and the first element as the current value; the
index of the first element is passed as the index
•
For subsequent calls to
callback
, the value returned from the
previous call is passed as the previous value; the current value
and index are the value and index of the current element
The
reduceRight()
method works the same as the
reduce()
method, except that it
processes the elements of the array from end to start. The following code shows how to
use the
reduce()
and
reduceRight()
methods to compute the sum of all numbers in an
array and to join elements of a string array:
var nums = [1, 2, 3, 4, 5];
// Defines a reducer function to compute sum of elements of an array
var sumReducer = function(previous, current, index, data) {
return previous + current;
};
var sum = nums.reduce(sumReducer);
print("Numbers :" + nums);
print("Sum: " + sum);
// Defines a reducer function to concatenate elements of an array
var concatReducer = function(previous, current, index, data) {
return previous + "-" + current;
};
Search WWH ::
Custom Search