When encountering the error message, it simply means that the pageBlock
array is empty, causing confusion on what to return from the reduce
function.
To resolve this issue, you must provide a starting value as the second parameter of the reduce
function.
For instance:
return pageBlock.reduce(value => value, null);
I would like to emphasize that your current implementation in the reduce function only returns the first value and disregards the rest. Is this the intended behavior? If so, you can simplify it by using:
return pageBlock[0]
--- A GUIDE ON UTILIZING THE REDUCE FUNCTION ---
The reduce
function takes in a callback with 2 arguments and an initial value. It cycles through the array in the following manner:
- step 1: callback(initialValue, array[0])
- step 2: callback(theResultFromStep1, array[1])
- step 3: callback(theResultFromStep2, array[2])
- ....
- step N: callback(theResultFromStep(N-1), array[N-1])
It then outputs the result from the last step. For example:
arr.reduce((a, b) => a+b, 0);
would yield the sum of all values in the array (assuming they are all numbers)
arr.reduce((a, b) => a+b, "");
would concatenate all values into a single string (similar to arr.join(''))
;
arr.reduce((a, b) => a*b, 0);
would give the product of all values in the array (provided they are all numbers)
arr.reduce((a, b) => a, null);
would return the first value in the array or null if empty
arr.reduce((a, b) => b, 0);
would output the last value in the array or null if empty
and so forth.