Some advanced uses of array reduce

aifou
8 min readApr 9, 2024

Reduce, as one of the commonly used array methods introduced in ES5, seems to be somewhat overlooked compared to forEach, filter, and map in practical use. I’ve noticed that very few people around me actually use it, leading to this powerful method gradually being forgotten.

If you frequently use reduce, how could you overlook its usefulness! I still need to bring it out of the dust and present its advanced usage to everyone. Such a useful method shouldn’t be buried by the masses.

Below is a brief explanation of the syntax of reduce, for more details refer to the relevant documentation on MDN.

- Definition: Executes a custom accumulator function on each element of the array, resulting in a single return value.
- Form: array.reduce((t, v, i, a) => {}, initValue)
- Parameters
— callback: The callback function (required)
— initValue: Initial value (optional)
- Parameters of the callback function
— total (t): The return value when the accumulator completes the calculation (required)
— value (v): Current element (required)
— index (i): Index of the current element (optional)
— array (a): The array object to which the current element belongs (optional)
- Process
— Use t as the initial value of the accumulator. If t is not set, the first element of the array is used as the initial value.
— Start iterating, use the accumulator to process v, accumulate the mapping result of v to t, end this loop, and return t.
— Enter the next loop, repeat the above operation until the last element of the array.
—…

--

--