DEV Community

Sushanta Gupta
Sushanta Gupta

Posted on

Easy Explanation of Reduce Function

Suppose we have an array of numbers, which is denoted by let A= [1,2,3]. We want to find the total of all array elements. In this case, we can use for loop.But we we may also use reduce function. We may also use the array.prototype.reduce function to do this task.

array.reduce function takes two arguments. One is a callBack function and other is initial value.

myArray.reduce(callBack,initialvalue)
Enter fullscreen mode Exit fullscreen mode

This callback function takes four arguments-previousvalue, current value,currentIndex, Array. The first two arguments are required, and the last two are optional.

const callBack = (
previousvalue, //required
currentvalue, //required
currentIndex, //optional
Array //optional
)=>{
}
Enter fullscreen mode Exit fullscreen mode

Example:

const myArray = [1,2,3]
const myFunc = (previous,current)=>{
return previous+current
}

const result = myArray.reduce(myFunc,0)
Enter fullscreen mode Exit fullscreen mode

The final result will be 6, but this result is dependent on the initial value.

We will try to understand why this result is dependent on the initial value. As there are three elements, reduce method will iterate three times.
In the first iteration, the previous-value and current-value is zero and one respectively. Finally, its sum is be stored in the total value. In the next iteration, the total value becomes the previous value, and the current value is the next array element, and its total is stored at the total variable. Thus the loop continues until the last array element.

iteration

Top comments (0)