The reduce()
method in Javascript is used to execute a function on each element of an array from left to right and reduce the array to a single value.
The reduce()
method takes two arguments, the first argument is a function and the second argument is the initial value of the accumulator.
To understand why we need an accumulator argument, we need to first understand how the function within the reduce()
method works.
The function takes a total of four arguments.
let numbers = [1, 2, 3, 4, 5],
initial_accumulator_value = 0;
numbers.reduce(function(accumulator, element, index, array) {
// code
}, initial_accumulator_value);
The first argument is the accumulator. The work of this function is to combine two values and return the accumulated value. The accumulated value is then passed back to the function as the accumulator value. You can specify the initial value of the accumulator as the second argument. For example, if you want to sum all the elements of an array, then, the accumulator’s initial value is 0
.
Before it gets too confusing, let us consider an example to see how it works.
We have an array numbers
with integers in it. Using the reduce()
method let’s return the sum of all the elements. The index
and array
arguments are optional and are not required for our example.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, element) {
return accumulator + element;
}, 0);
console.log(sum); // 15
The result returned by the reduce()
method is 15
which is the sum of the elements in the array numbers
. Notice, that the second argument of the reduce method is 0
. This is the initial value of the accumulator. So, in the first iteration 0
is added with the first element i.e, 1
and the total is 0+1 = 1
. The value 1
is now gets assigned to the argument accumulator
and in the second iteration, we have 1 + 2 = 3
and so on.
Iteration | accumulator | element | return(accumulator + element) |
---|---|---|---|
1 | 0 | 1 | 1 |
2 | 1 | 2 | 3 |
3 | 3 | 3 | 6 |
4 | 6 | 4 | 10 |
5 | 10 | 5 | 15 |
If we assign the initial value of the accumulator as 100
the result will change accordingly.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function(accumulator, element, index, array) {
return accumulator + element;
}, 100);
console.log(sum); // 115
Let us take another example with elements of the array as objects. We have an array of objects employees
with name
and age
as the property. Suppose if we want to add the sum of all the ages of employees
we can do so using the following code:
let employees = [
{
name: "mickey",
age: 10
},
{
name: "Donald",
age: 12
},
{
name: "Minnie",
age: 8
},
{
name: "Pluto",
age: 5
}
];
let totalAge = employees.reduce(function(accumulator, employee) {
return accumulator + employee.age;
}, 0);
console.log(totalAge); // 35
The totalAge
stores the sum of all the ages of the employee.