Quirrel4.41.0

types.Array.reduce

Method on every array
array.reduce(callback: function, [initial], ...): any

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

callbackfunctioncallback(accumulator, value, [index], [array]), combines the accumulator with the next element
initialanythe 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

examples/types/array/reduce.nut
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 = 42

See also

mapBuilds a new array from the results of callback on each element.
eachCalls callback once per element, in order.
arrayclass index