Array.reduce()
reduce()
- This method executes a given "reducer" callback function on each element of array in order with a twist: Each return value is an input for the next element. It's accumulative.
- The return value from an element operation will be passed to the next element as an argument.
- An initial value can be given to be used as the previous value for the first element.
- So the return value of each element along the way represent an accumulative value.
- Meanwhile, the previous value doesn't need to be in the array anymore since its value has been represented in the accumulative result. Therefore, "reduced".
- The final result is a single value.
- The return value from an element operation will be passed to the next element as an argument.
-
reduce(...)
- Syntax
-
// Callback function reduce(reducerFn) reduce(reducerFn, initialValue) // Inline callback function reduce(function (prev, val) {...}) reduce(function (prev, val, index) {...}) reduce(function (prev, val, index, array) {...}) reduce(function (prev, val, index, array) {...}, initialValue) // Arrow function reduce((prev, val) => {...}) reduce((prev, val, index) => {...}) reduce((prev, val, index, array) => {...}) reduce((prev, val, index, array) => {...}, initialValue)
-
- Parameters (2):
-
reducerFn
: The reducer functioninitialValue
(optional):- If specified: It will be used as the
prev
for the first element. - If not specified, the first element run will be skipped, and the first element value is used as the
prev
for the second element run.
- If specified: It will be used as the
- Return value:
- The final accumulative value
- Original array:
- Not changed (unless manipulated by accessing the array during callback)
- Reducer function
-
function reducerFn(prev, val, index, array) { ... return newValue; } // "newValue" is the "prev" for the next element.
-
- Parameters (4):
-
prev
: The return value of the previous element run, aka the accumulative value. For the first element, will use theinitialValue
if supplied.val
: The current element's value.index
: The index of current element.array
: The array being worked on.
- Return values:
- The accumulative value up to current element.
- Example: sum
-
const nums = [1,2,3,4,5]; const sum = nums.reduce((prev, val) => prev + val); sum; // 15