In Google Apps Script, the reduce()
The array method applies a function to each element in an array to reduce the array to a single value. The method takes a callback function as an argument, which calls for each array element. The callback function should return the accumulated result of the previous iterations and the element’s current value.
Here is an example of using the reduce()
method to sum up the elements in an array:
var numbers = [1, 2, 3, 4, 5];
// Sum up the elements in the numbers array
var sum = numbers.reduce(function(acc, curr) {
return acc + curr;
}, 0);
// Output the sum
Logger.log(sum); // Outputs: 15
In this example, we call the reduce()
method on the numbers
array and pass a callback function that sums up each element. The method iterates over each element in the array and calls the callback function for each element, passing the accumulated result of the previous iterations and the element’s current value as arguments. The callback function adds the accumulated result and the element’s current value, and returns the sum as the new accumulated result. The initial value of the accumulated result is set to 0
in this example. The reduce()
method returns the final accumulated result, which is assigned to a variable called sum
, and is outputted to the log using the Logger.log()
method.
You can also use the reduce()
method to find the maximum value in an array:
var numbers = [1, 5, 3, 4, 2];
// Find the maximum value in the numbers array
var max = numbers.reduce(function(acc, curr) {
return acc > curr ? acc : curr;
}, numbers[0]);
// Output the max value
Logger.log(max); // Outputs: 5
In this example, we call the reduce()
method on the numbers
Array and pass a callback function that finds the maximum value. The method iterates over each element in the array and calls the callback function for each element, passing the accumulated result of the previous iterations and the current value of the element as arguments. The callback function checks whether the accumulated result is greater than the element’s current value and returns either the accumulated result or the element’s current value as the new accumulated result. The initial value of the accumulated result is set to the first element in the array numbers[0]
in this example. The reduce()
method returns the final accumulated result, which is the maximum value in the array, and is assigned to a variable called max
, and is outputted to the log using the Logger.log()
method.