DEV Community

Sushanta Gupta
Sushanta Gupta

Posted on

2 2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️