Array.prototype.reduce()
reduce() is considered by some Javascript beginners to be one of the most confusing array methods. In this tutorial I will present the method in a way that is easily understood, so you can start experimenting with reduce()
in your own code. We'll start by taking a macroscopic view of the method, then break it down into digestible bite-sized chunks to understand how each individual part works.
Description
reduce()
is an Array method that executes a "reducer" callback function on each element of the target array. The "reducer" callback function must return a single value for use in the next callback method on each subsequent array element.
Returns
After reduce()
iterates over the last array element, the method returns the result of the final "reducer" callback function.
I personally interpret that the method is called reduce
because it will iterate over every individual element of an array, but ultimately the method only returns one single value after traversing the entire array.
Destructive?
The reduce()
method itself does not directly mutate the array it is called on, so it is not considered a destructive method. However, it's important to note that the callback function might call destructive methods that could mutate the original array.
Syntax
The syntax of the reduce()
function itself is very simple:
const numbers = [1, 2, 3];
numbers.reduce(callbackFn, initialValue);
Note: The second parameter,
initialValue
, is optional and not required for the function to run.
As you can see from above, the syntax to implement reduce()
is not confusing at all. I found the complexity of using reduce()
comes from the requirements of the "reducer" callbackFn
that is passed into the method. So, let's dive into the syntax of the callback function now.
Here is an example "reducer" callback function that will sum all elements of an array:
const reducer = function(accumulator, currentElement) {
return accumulator + currentElement;
}
Note: Similar to other array methods, it is possible to pass two additional parameters to the callback function. The 3rd parameter passed represents the current index of the array, and the 4th parameter represents the array being traversed.
Here's how each element works:
-
accumulator
: This parameter "accumulates" the results of each execution of the callback function. The value that is returned by the preceding callback function becomes the accumulator value in each execution of the callback function.
Note: By default if no
initialValue
is passed in thereduce()
function, thenaccumulator
is initially set to equal the first element of the array.
-
currentElement
: This parameter represents the value of the current array element that is being iterated over.
Still confused?
Not to worry, let's go into a simple example together and I'll explain how all of these moving pieces work together in the reduce()
method.
Example Breakdown
The most basic implementation of reduce()
is to return the sum of all the elements in an array. To start, let's sum up the following odd numbers.
const numbers = [1, 3, 5, 7];
const reducer = function(accumulator, currentElement) {
return accumulator + currentElement;
}
console.log(numbers.reduce(reducer));
This code snippet will "reduce" the array of numbers into a single number by adding them together. The expected result is 16
because 1 + 3 + 5 + 7 = 16
.
Let's break this example down to make it more simple.
- To start, we call
reduce
on thenumbers
array and we pass in the callback functionreducer
as a parameter intoreduce
. - We did not pass the 2nd optional parameter,
initialValue
, into thereduce()
function. So, for the first execution ofreducer
theaccumulator
is set to the value of the first element in the array andcurrentElement
is set to the value of the second element in the array.
Here's what the first call of reduce()
looks like with the reducer
callback parameters replaced with array elements:
reducer(numbers[0], numbers[1]) {
return numbers[0] + numbers[1];
}
Now written with the values in place of the parameters:
reducer(1, 3) {
return 1 + 3;
}
After the initial call of the reducer
callback function, reduce()
iterates to the next array element executing the reducer
callback function over and over until it reaches the end of the array.
Here's a breakdown of the next call of the reducer
callback function. This time accumulator
is set to equal the returned result of the previous callback function.
reducer(4, numbers[2]) {
return 4 + numbers[2];
}
Now written with the values in place of the parameters:
reducer(4, 5) {
return 4 + 5;
}
Are you getting the pattern yet? The accumulator
simply accumulates the result of the previous callback function and uses it in the next execution of the callback. So for our final call of the example, the accumulator
will be equal to 9
as that is the returned value of the previous callback function.
reducer(9, numbers[3]) {
return 9 + numbers[3];
}
Now written with the values in place of the parameters:
reducer(9, 7) {
return 9 + 7;
}
This was the final call of the reducer
callback function because we have now iterated over each array element, so 16
will be the value returned from the original reduce
method called on the numbers
array.
Other Uses of reduce()
As you saw from the example above, reduce()
is very effective at returning the sum of all elements in an array. You might be wondering what other practical uses exist for reduce()
. Here are a few:
- Sum values in an object array
- Flatten an array of arrays
- Replace .filter().map()
- And more!
Challenge
Want more practice? Try to code the following challenge:
Using reduce(), write an implementation that will return the sum of all even numbers in an array.
Hint: You must use a conditional statement in your callback function.
Top comments (0)