🥘 Reduce: It's all gravy, baby!
Patrick Canella
Posted on August 22, 2022
I've been working in JS codebases for over 10 years (👴🏻) and one thing that still trips me up sometimes is the reduce
function. Every time, I go to the MDN documentation on reduce
, I have some initial trouble understanding how the heck it works.
Then, if you go on Twitter or something, everyone will be like "reduce is the most important array function!" Cue anxiety 😩!
So in this short post, I'll try to explain Reduce and show examples that are actually relevant and not overwhelming.
So with that; let's REDUCE 🥘.
Let's start with the "official" documentation explanation and go from there:
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
From this we know:
- It takes in a callback function
() => {}
for each array element - It takes the previous calculated element and uses it in the callback function. Like so
(previousValue, currentValue) => {}
- It returns a new array of values after reducing
- We don't know this really, but
reduce
is a really stupid name for this function. IMOaccumulator
would be a far better, and more accurate term.
One thing to note is that reduce
will take a callback, but it will also take an initial value
as a parameter; this is to "get the accumulator going" in the right direction. If you're adding/manipulating numbers, it's a good idea to start at 0
.
As an example, it'll look like this:
// This is incredibly similar to the MDN example
const arrayToReduce = [1, 2, 3, 4, 5];
arrayToReduce.reduce((prevValue, currValue) => return prevValue + currValue), 0)
But let's take MDN's example and break it down a bit. Complete with console.logs to make a bit more sense of how it works:
const initialValue = 0;
const arrayToReduce = [1, 2, 3, 4, 5];
arrayToReduce.reduce(
(previousValue, currentValue) => {
console.log("prev:", previousValue, "curr:", currentValue);
const result = previousValue + currentValue;
console.log("result", result);
return result
},
initialValue
);
Running this will output the following:
> "prev: " 0 "curr:" 1
> "result" 1
> "prev: " 1 "curr:" 2
> "result" 3
> "prev: " 3 "curr:" 3
> "result" 6
> "prev: " 6 "curr:" 4
> "result" 10
> "prev: " 10 "curr:" 5
> "result" 15
> 15
I feel like explaining this without an example showing the output and everything is disingenuous. As you can clearly see here, basically the result
is added to the next iteration as an input in the callback (previousValue
), and the current iteration that the array is looping through, is the currentValue
.
This is basically the equivalent of doing:
const arrayToForLoop = [1, 2, 3, 4, 5];
let valueToKeepTrackOf = 0; //equivalent to reduce's "initialValue" parameter
let finalResult = [];
arrayToForLoop.forEach(item => {
console.log("prev:", valueToKeepTrackOf, "current:", item);
valueToKeepTrackOf += item;
console.log(valueToKeepTrackOf);
finalResult.push(valueToKeepTrackOf);
});
console.log(finalResult);
So there you have it! That's reduce
in a nutshell. It's incredibly useful for appending/using operators on!
My personal advice: Don't use this for complex things; if you need to do something really complex or nested in a bunch of JSON objects, best to simplify it first and go from there.
As always, MDN is a great source to understand this in its entirety.
Cover Photo Credit: La Cucina Italia
Posted on August 22, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.