Today's progress
Learned a little bit more about the reduce()
method.
What I learned
The reduce()
executes a provided function for each element in an array Reducing the array to a single value. The return value of the function is stored in accumulator (result/total).
For better explanation, let's go ahead dive into some code.
We have this array of numbers and inside the array we have all of these elements and we want to get the sum of all the elements. A typical for loop
iterating over each element and adding them can solve this.
In addition, we can use the reduce()
method to sum up all the elements in the array and returning a single value.
let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(function(sum, number){
return sum + number;
})
console.log(total)
//output: 15
In the code above we have the reduce()
with a callback function
that takes in two parameters. The first parameter being the sum (accumulator), which is the accumulated value. The second parameter, number
is the currentValue
being processed.
Here's a good example of what is happening under the hood.
let numbers = [1, 2, 3, 4, 5]
let total = numbers.reduce(function(sum, number){
console.log("the accumulator is: " + sum, "the element's value is " + number)
return sum + number;
})
//output: the accumulator is: 1 the current value is 2
// the accumulator is: 3 the current value is 3
// the accumulator is: 6 the current value is 4
// the accumulator is: 10 the current value is 5
Using the same code example as before but this time adding a console.log
before our return
statement. So we can visually see what is happening in each iteration.
Notice on the first iteration the accumulator
is the value 1
and the second parameter current value
is 2
. Then on each iteration the accumulator
becomes the sum of the previous accumulator
and current value
.
Filling in the gaps
The complete syntax for reduce()
is as follows:
array.reduce(function(accumulator, currentValue, index, array){...})
Simply put
The reduce()
method helps to return a single value from an array, as a result of sequentially processing the results of the previous elements.
Top comments (0)