types.Array.reduce
Folds the array down to one value by repeatedly combining an accumulator with each element.
The binding carries no declaration string, so the VM cannot report parameter names. The names above are from this page; the types and attributes still come from the VM. The VM also cannot tell an optional parameter from a variadic tail here, so read the brackets and any trailing
... from the prose below, not from the signature.Parameters
callback | function | callback(accumulator, value, [index], [array]), combines the accumulator with the next element |
initial | any | the accumulator's starting value; the first element when left out optional |
... | any | repeats |
Return value
The final accumulator. On an empty array: initial if it was given, otherwise null, either way without calling callback.
Errors
Whatever callback throws, on the first element where it throws.
Notes
callback gets exactly as many of the arguments listed above as it declares parameters for, and never more. index and array count the element supplying value, which starts at index 1 when initial was left out, since element 0 seeded the accumulator instead of being folded in.
When initial is left out and the array has exactly one element, that element is returned as is and callback is never called.
Example
println("reduce([1, 2, 3]), no initial =", [1, 2, 3].reduce(function(a, b) { return a + b }));
println("reduce([1, 2, 3]), initial 10 =", [1, 2, 3].reduce(function(a, b) { return a + b }, 10));
println("reduce([7]), no initial =", [7].reduce(function(a, b) { return a + b })); // one element: callback never runs
println("reduce([]), no initial =", [].reduce(function(a, b) { return a + b }));
println("reduce([]), initial 42 =", [].reduce(function(a, b) { return a + b }, 42));Output:
reduce([1, 2, 3]), no initial = 6
reduce([1, 2, 3]), initial 10 = 16
reduce([7]), no initial = 7
reduce([]), no initial = null
reduce([]), initial 42 = 42See also
map | Builds a new array from the results of callback on each element. |
each | Calls callback once per element, in order. |
| array | class index |