DEV Community

The Builder
The Builder

Posted on • Updated on

JavaScript reduce method and how it works

The reduce array method is an interesting method because unlike filter and mapthat takes one parameter during it's most basic usage, the reduce method takes two parameters. The first one is the accumulator and the other is the parameter of the current value that will be worked on.

reduceallows for items to be summed up or brought together.

Let's see a few examples on it.

Were going to try to sum up the numbers in the following array:

const nums = [1, 2, 3, 4, 5]

Solution

const sumNumbers = nums.reduce((sum, num)=> sum + num, 0)

console.log(sumNumbers)

//output is 15

Here, you will see that apart from num which is the current value parameter that we will work on according to every number in the array, the sum which is another parameter and the accumulator taken in by reduce and it is being set to an initial value of 0at the end of the reducemethod so that it can be added to the current value numand accumulated as it moves along the from one number to the other in the array.

Example 2

Apply reduce and add "-" at the end of every city in the array.

const cities = ["Lagos", "Paris", "Miami", "Mumbai" ]

Solution

const dashCities = cities.reduce((result, city)=> result + city + "-", "")

console.log(dashCities)

//output is Lagos-Paris-Miami-Mumbai-

Here we can see that the cities are brought together with dashes after them and made into a string because result which is a parameter and the accumulator has an initial value that is set to an empty string at the end of the reducemethod.

I hope you enjoyed the explanation and now understand how reduceworks now. Please like, share, comment and follow for more.

Top comments (0)