A guide to Array.reduce() Method in JavaScript

The reduce() method reduces the array to a single value. This method takes one reducer function as the first argument and one initial value as the second optional argument. The reducer function executes for each element of the array and passes the returned result as the first argument (accumulator) to the next reducer function call.

array.reduce(reducerFunction, initialValue);

The reducer function takes two required arguments named accumulator and currentValue. The accumulator is either the initial value or the previously returned value, whereas the currentValue is the element upon which the reducer function is executing in the current iteration.

function reducerFunction(accumulator, currentValue, currentIndex, array) {}

The reducer function also takes two optional arguments named currentIndex and array. The currentIndex is the index of currentValue in the array, and the argument array is the original array upon which the reduce() method is called.

How the reduce() method works

Let’s see one example to sum all the values of an array.

const numbers = [25, 48, 13];

const total = numbers.reduce(reducerFunction);

function reducerFunction(result, current) {
    return result + current;
}

console.log(total); // 86

So here, the reducerFunction gets called the first time with 25 and 45 as the arguments and returns 73. The next time reducerFunction gets called with previously returned value 73 and 13 and returns 86.

We can provide console.log before the return statement and check how many times the reducerFunction is getting called and the values of the arguments passed.

function reducerFunction(result, current) {
    console.log(`result:${result} current:${current}`);
    return result + current;
}

The output of the reducerFunction will be:

result:25 current:48
result:73 current:13

If we pass an initial value to the reducerFunction, then for the first call, the initial value will be the first argument, and the first element of the array will be the second argument.

const numbers = [25, 48, 13];

const initial = 0;

const total = numbers.reduce(reducerFunction, initial);

function reducerFunction(result, current) {
    console.log('result:' + result, 'current:' + current);
    return result + current;
}

console.log(total); // 86

output

result:0 current:25
result:25 current:48
result:73 current:13
86

Let’s see some more examples of the reduce() method.

Find max and min numbers in an Array

Let’s see how we can find both max and min numbers in an array using reduce() method.

const numbers = [25, 48, 13, 83, 59];

const maxNumber = numbers.reduce((max, current) => {
    return max > current ? max : current;
})

console.log(maxNumber); //83

Similarly, we can find the minimum number by changing the reducer function as below:

let minNumber = numbers.reduce((min, current) => {
    return min < current ? min : current;
});

Convert Array to Object

Suppose we have an array of student objects where every student object has a name and semester marks.

let students = [
    {name: 'Joey', marks: 41},
    {name: 'Monica', marks: 83},
    {name: 'Ross', marks: 92},
    {name: 'Rachel', marks: 51},
    {name: 'Chandler', marks: 76},    
    {name: 'Pheobe', marks: 45}
]

Now, we will create one object from this array by keeping the student’s name as the key, and their marks as the value. Let’s see how to do that with reduce().

let result = students.reduce((obj, student) => {
    obj[student.name] = student.marks;
    return obj;
}, {});

console.log(result);

output

{
    Joey: 41,
    Monica: 83,
    Ross: 92,
    Rachel: 51,
    Chandler: 76,    
    Pheobe: 45
}

The Array.reduceRight() method

This method works the same way as the reduce() method, but unlike reduce(), it executes from right to left.

const numbers = [25, 48, 13];

const total = numbers.reduceRight((result, current) => {
  console.log(`result:${result} current:${current}`);
  return result + current;
});

console.log(`total:${total}`);

// result:13 current:48
// result:61 current:25
// total:86

map() and filter() methods of Array in JavaScript

3 thoughts on “A guide to Array.reduce() Method in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *