Do you know you could actually use the same reduce method you have always used to return the sum for chaining together your promises or to even compose functions?
The reduce method is one of the most powerful array methods used in JavaScript alongside fellow avengers - the filter and map method.
Being this powerful also means it's rarely understood by budding developers like me while being scarcely adopted by mainstream JavaScript developers.
Today, we're taking a look at its traditional usage for summing up values as well as two more interesting use cases later in the article.
What is the Reduce Method?
According to MDN
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.
Similar to map, filter, and forEach, the reduce method allows us to iterate through our array, taking a callback function on each item and then returning a single value.
Interestingly, this single value can be anything from - number, array, or even an object.
1. The Accumulator Function
Obviously, the most common example known to man!
Now, saying this is common might be relative but, this has to be the most basic use case of the reduce method out there on the web.
Let's say we have an array of objects and we are looking to get the sum of the salary so we can make a decision on why the intern is getting $30 while the boss takes home $400.
// Array of objects
const staff = [
{name: 'bob', age: 20, position: 'developer', salary: 100},
{name: 'peter', age: 25, position: 'designer', salary: 300},
{name: 'susy', age: 30, position: 'CEO', salary: 400},
{name: 'anna', age: 35, position: 'intern', salary: 30}
]
Here's one way to use the reduce method:
const totalSalary = staff.reduce((total, currSalary) => {
total = total + currSalary.salary
return total
}, 0)
NB: Always return the first parameter!
Here, we are creating a new variable with the name totalSalary
and using the reduce method which takes two parameters - total, currSalary.
Now, these two parameters can be named anything but essentially, the accumulator - total
and currSalary
refers to the sum of iteration and the current item being iterated at a given time respectively.
The total
exists to hold the sum of each round of iteration while currSalary
identifies the next item in the loop to be iterated on.
We also have to define the starting position of our loop and that's why we have 0 at the end of our callback function so our count starts from.
In essence, here's what we're getting as a result from the function above:
// console.log(total); 0, 100, 400, 800, 830
// console.log(currSalary.salary); 100, 300, 400, 30
console.log(totalSalary), // 830
And just like that, you have the sum of salary paid out to employees in little to no code.
However things get interesting from here :)
More reduce method plsss...
If you've only known and used the reduce to return the sum of values in an array, then check this space onwards for some magic!
2. Chaining Together Promises
The async keyword when managing long-running tasks might be the best thing that ever happened to JavaScript.
In the way that it helps us group individual task in a function which can be passed into the next function.
But, what of a situation you intend to use something asides the async keyword, and intend to achieve a clean code devoid of the popular callback hell.
Using the reduce method in your function can be an option in achieving same purpose and ultimately helps you manage the different phase of each task iteration?
Let's say we have local api containing some IDs:
let itemIDs = [1, 2, 3, 4, 5]
One way we could chain together our promises without using the regular .then
function is this:
const itemSum = itemIDs.reduce(async (promise, itemID) => {
const item = await promise
return item.deleteItem(itemID)
}, Promise.resolve())
Now, essentially what we are doing is nothing more than your regular chain of .then commands like this:
Promise.resolve()
.then((item) => item.deleteItem(1))
.then((item) => item.deleteItem(2))
.then((item) => item.deleteItem(3))
.then((item) => item.deleteItem(4))
.then((item) => item.deleteItem(5))
3. Composing Functions
The reduce method can also be used to compose our functions i.e define how and what direction we want the iteration to work.
The reduce method is popularly known for acting as an accumulator but the gimmick is, that it always sorts the array from left to right.
How about we define this in our own way by composing a function using reduce() and passing along the result to the next running function?
This example is one I've jacked from Bojan Gvozderac and his post on reduce, filter and map methods.
We could have something interesting as this;
let double = [1, 2, 3, 4, 5]
const compose =
(...double) =>
(n) =>
double.reduceRight((v, f) => f(v), n)
Now, this is really mind-blowing, which I've had quite a tough time grasping.
But, this is the trick:
We have a variable compose - which is partially applied using the rest parameter so that we can compose as many functions as we want and all of them will be put in the double
array.
Next, we pass an initial value n
after which we now use the reduceRight
together with the initial value n
to define the starting position of or composed function.
It might get confusing but, this is the same as the reduce
method in the first example only that the accumulator starts counting from the end of the array and then moves to the start using the (f, v)
parameter.
Awesome confusion right!
Conclusion
The reduce method is one hell of a method to use in different ways and with JavaScript without a definite structure, your guess...
However, the amazing thing is that it passes the result of the callback function to the next allowing us to manipulate array data in different ways.
Now, we have looked at really awesome use cases of the reduce method as well as a viable practice to employ when working with Api data.
However, I would love to know which of these you have applied in a project of yours before.
Also, If you know more fun and creative ways to use the reduce method, I’d really be glad to know about them in the comments😊
If you liked this article, consider giving me a follow and also check out my Twitter as I take you through my journey learning JavaScript’ for frontend development.
https://github.com/trillionclues
Thank you for reading!❤️
Top comments (3)
Very well captured 💪💪
Thanks Victoria! Glad you found it insightful.
Very nice.