The concept of the reduce function as outlined in the text is quite interesting:
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}
When used as a method of an array, it looks like this:
arr.reduce(combine, start);
Breaking down the reduce
method, it essentially involves "folding up the array, one element at a time," as described in the book. The first argument passed to reduce
is the "combiner function," which takes two arguments: the "current" value and the "next" item in the array.
The initial "current" value is determined by the second argument of the reduce
function. In the case of flattening arrays, this initial value is represented by the empty array, []
. Initially, the "next" item in the array is the first item (index 0).
According to the book, "If your array has at least one element, you can omit the start argument."
In the context of the flattening solution, it may be a bit confusing that current
is positioned as the second argument in the reduce
method, while in the definition of reduce
provided earlier, current
is used to store the cumulative, folded value. In the flattening solution, however, current
actually represents the "next" item in the arrays being processed (each individual array of integers).
Throughout the reduction process, the current value combined with the next array item is passed to the combiner function, and the resulting value becomes the updated "current" value. Essentially, each element of the array is consumed and the process continues with the next item.
The variable flat
simply serves as the name for the accumulated result. Given the goal of returning a flat array, this name is fitting. Since arrays have the concat
function, the initial step in the reduce
function would be (assuming internal variables could be directly assigned):
flat = []; // (assigned as the second argument to reduce)
As the reduction progresses through the arrays, we can simulate it based on the steps outlined in the reduce
function:
for (var i = 0; i < arrays.length; i++)
flat = combine(flat, arrays[i]);
When combine
is called, we get
[].concat([1, 2, 3]) // => [1, 2, 3]
Subsequently, we have:
flat = [1, 2, 3].concat([4, 5]) // => [1, 2, 3, 4, 5]
This process continues for each iteration of the reduction. The final result returned by the reduce
function will be the value of flat
at the end.