Sumit | Javascript + React
Sumit | Javascript + React

@sumitsaurabh927

14 Tweets 3 reads Mar 02, 2023
Javascript explained:
reduce() method in Arrays!
If you're a JavaScript developer, you've likely come across the reduce() method of arrays at some point.
But do you know how to use it effectively?
Let's explore what it does and how it works!
At its core, reduce() is a method on arrays that takes two arguments:
βœ… a reducer function, and
βœ… an optional initial value.
The reducer function is called on each element of the array and returns a single accumulated value.
Here's an example:
Let's say we have an array of numbers, and we want to sum them all up. We can use reduce() to accomplish this:
In this example, we pass a reducer function to reduce() that takes two arguments:
βœ… an accumulator (acc), and
βœ… a current value (curr).
On each iteration of the loop, the reducer function adds the current value to the accumulator.
The second argument to reduce() is the initial value of the accumulator.
In this case, we pass 0 as the initial value, so the accumulator starts at 0 and adds each number in the array to it.
But reduce() is capable of much more than just summing up an array of numbers.
You can use it to perform all sorts of operations on an array, like:
βœ…finding the maximum or minimum value,
βœ… filtering out certain elements, or
βœ… transforming the array into a different shape.
Let's look at another example:
Suppose we have an array of strings, and we want to create an object that maps each string to its length.
We can use reduce() to accomplish this:
In this example, we pass an empty object as the initial value to reduce().
On each iteration of the loop, the reducer function adds a new key-value pair to the accumulator object, where the key is the current word and the value is its length.
As you can see, reduce() is a powerful method that can simplify your code and make it more concise.
But like any powerful tool, it can be misused or overused.
Before using reduce(), make sure you understand how it works and what it's doing.
That's it for this introduction to reduce()
I hope you found it helpful.
Give it a try in your own code, and see what you can accomplish with this versatile method.
You can take a look at the threads I've written for other array methods.
Here's the one on filter() method:
Here's the thread on slice() method:
That's a wrap!
Hey, I write two threads every day on web dev and it takes a lot of time and effort.
So, I'd be glad if you could spare me a minute to:
βœ… Follow me @sumitsaurabh927 for more of these.
βœ… RT the tweet below to show me some love.

Loading suggestions...