Basics Of JavaScript Reduce() Method

The reduce() method is one of Javascript's array method. As a JavaScript developer, the reduce() method comes in handy when working with arrays. In this article, I would try my best to explain the basics behind the reduce() method and how it works.

Lets take a look at what a reduce() method can do:

//A simple reduction of an array
//Finding the sum of an array
const arr = [1, 2, 3, 4, 5]
const arrSum = arr.reduce((acc, curr) => {
    return acc + curr;
}, 0)
//returns 15

The reduce() method takes a callback function and an initial value as its parameters. It executes this callback function and provides a single output. The callback function is executed on every member of the array and it's usually called a reducer.

array.reduce(callback, initialValue)

If the initial value is not specified, the first member of the array (index of 0) is taken as the initial value and the callback function starts its execution from the index of 1 leaving out the first member of the array.

//The initial value is not provided
//Finding the sum of an array
const arr = [10, 20, 30, 40, 50]
const arrSum = arr.reduce((acc, curr) => {
    return acc + curr
})
//arrSum = 150

The reducer(callback function) takes in four parameters

array.reduce(
    function(accumulator, currentValue, Index, SourceArray) {
})

Accumulator

The accumulator as its name implies accumulates the output of every successful execution of the reducer. The accumulator is what distinguishes the reduce() method from other JavaScript array methods. The accumulator is the output of the last successful execution of the reducer or the initial value(on the first call).

Current Value

This is the current element been processed by the reducer.

Index

This is the index of the current element been processed by the reducer, specifying it is optional. The reducer executes from index 0 if an initial value is specified or index 1 if no initial value is specified.

Source Array

This is the array the reduce method is called upon. Specifying it is also optional.

Breaking It All Down

Let's take a look at how reduce() works

/* Suppose you have an array of objects of workers in an organisation, And all you need is the name of the workers in a single array */

array = [
    {name: 'Jeff'},
    {name: 'Orpheus'},
    {name: 'Mark'},
    {name: 'Motun'},
    {name: 'Tomisin'},
    {name: 'Abesh'}
]

array.reduce((acc, curr) => {
    const arrayName = acc.concat(curr.name)
    return arrayName;
}, [])

/* returns [ "Jeff", "Orpheus", "Mark", "Motun", "Tomisin", "Abesh" ] 
*/

Observing this use case an empty array is specified as the initial value.
Let's take a look at what the reducer is doing - Since an initial value is provided the reducer starts its execution on the index of 0, and our accumulator would have an initial value of [].

First Execution/Call

acc = [];    //accumulator
cur = {name: 'Jeff'};    //current value index 0
arrayName = [].concat('Jeff');

// outputs  ['Jeff']
// output becomes accumulator on second call

Second Execution/Call

acc = ['Jeff'];    //accumulator
cur = {name: 'Orpheus'};    //current value index 1
arrayName = ['Jeff'].concat('Orpheus');

/* outputs  ['Jeff', 'Orpheus']
output becomes accumulator on second call */

Third Execution/Call

acc = ['Jeff', 'Orpheus'];    //accumulator
cur = {name: 'Mark'};    //current value index 2
arrayName = ['Jeff', 'Orpheus'].concat('Mark');

/* outputs  ['Jeff', 'Orpheus', 'Mark']
output becomes accumulator on Fourth call */

The reducer executes on and on until it gets to the last element of the array. For each successful execution of the reducer, the output becomes the accumulator for the next execution until the reducer executes on all the elements of the array and then gives a final output.

Note

  • reduce() method throws a TypeError when called on an empty array
  • If the array has a single element the reduce() method returns the single element
  • If the array is empty but an initial value is provided the initial value is returned without calling the reducer.

For further reads and advance concepts on reduce() method

Thanks for reading ☺️

Amarachi Emmanuela Azubuike's photo

Coincidentally, I googled about the reduce method just last night, so waking up to this well explained article already made my day. Thanks for breaking down this topic.

I have a question though. In the 2nd example you gave were we had

const arr = [10, 20, 30, 40, 50]
const arrSum = arr.reduce((acc, curr) => {
    return acc + curr
})

You said the output was going to be 150

I find this quite confusing since you also stated that if an initial value is not stated just as above, the reducer starts from index 1 which in this case is 20.

So shouldn't the result be 140 instead of 150?

Barnabas Asha's photo

I'm glad you liked the article, In the case where an initial value is not specified the reducer starts from index 1 and the first member of the array (index 0) is taken as the accumulator for the first execution.

arr = [10, 20, 30, 40, 50]
callback = function (acc, cur) {
return acc + cur
}

arr.reduce(callback)

/* first instance: 10 is taken as the initial val since one isn't specified and used as the accumulator 
So the callback returns */

return 10 + 20

/* Then 30 becomes the accumulator for the next execution. And it goes on */

I hope I was able to shed more light and not confuse you. Feel free to reach me.

Edidiong Asikpo's photo

This is really amazing for a first article Barnabas Asha. Keep up the good work. I can't wait to read your next article.

Barnabas Asha's photo

Thank you Didi

Efereyan Karen Simisola's photo

Boss πŸ™πŸΎπŸ™πŸΎπŸ™πŸΎ

Barnabas Asha's photo

You taught me well ma

Temiogundeji's photo

Nice article bro! Keep it up.

Barnabas Asha's photo

Thanks boss

Nwafor Uchechukwu's photo

Nice article πŸ‘