Basics Of JavaScript Reduce() Method

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 ☺️