How .reduce() Works
When first learning about the reduce method it is a little intimidating. In this article we breakdown the method with some simple examples, and create a reduce method of our own. Let’s get started…
What does the reduce method do?
The reduce method executes a particular operation on all elements of an array, each time combining the previous outcome with the current element’s value.
The reduce function accepts up to five parameters:
1–4. The callback function that we will be performed on each element or currentValue. The callback function takes in:
- accumulator (REQUIRED): starts as the initialValue (if provided), or the previous returned value of the callback function
- currentValue (REQUIRED): the value of the current element
- currentIndex (OPTIONAL): the index of the current element, starts from index 1 or 0 (if an initialValue is provided)
- arr (OPTIONAL): the array object the current element belongs to
5. initialValue (OPTIONAL): the value to be passed to the function as the initial value
The typical reduce function will look something like this:
array.reduce( callback( accumulator, currentValue, currentIndex , array ), initialValue )Example One: arr = [1,2,3]arr.reduce(( accumulator, currentValue ) => accumulator + currentValue )ORconst arraySum = ( accumulator, currentValue ) => { return accumulator + currentValue}arr.reduce(arraySum)OR //have access to all arguments in the function arr.reduce(( accumulator, currentValue, currentIndex , array ) => { return accumulator + currentValue}, 0 ) //all functions return 6
To better understand how this work we can make a simplified reducer function of our own. In this function the we will have three arguments. The array, callback function, and the initialValue.
- The accumulator will start at 0, or whatever initialValue is provided
- The next step is to iterate through our array, and for each currentValue or element in the array (array[i]) we call the callBack function.
- The callBack function will then perform an operation that combines the output of the currentValue (current element) and accumulator (previous return value)
Example Two ("home made" reducer function): arr = [1,2,3] const arraySum = (accumulator, currentValue) => accumulator + currentValue;
const myReduce = (array, callBack, initialValue = 0) => { let accumulator = initialValue for (let i = 0; i < array.length; i++) { let currentValue = array[i] accumulator = callBack(accumulator, currentValue) } return accumulator}myReduce( arr, arraySum, 0 )