Reduce Function in JavaScript

Jagadhiswaran D
2 min readNov 1, 2021

--

Reduce Function in JavaScript:

Reduce Function Is the Most Confused Function among the Developers in the beginning But later on Practicing it it becomes the most easy and useful in many of the application. The Reduce Function Walks through the array element by element at each step The Reducer Function Takes Two parameter accumulator and Current value. The Accumulator Indicates the Array And the Current Value Indicates the Value in the array.

Program

The above Example Has Two Set Of arrays with one named Mobiles and supermarket

the First example is about a simple array to add the values using the reduce function. for this first create function called sum with parameters anything as you like and return the sum logic to get the value and use reduce function in the array to get the sum of the array this function can be used for any array for adding the values using reduce.

the second example is about the supermarket array and I have added the total cost of the purchase in the array using reduce function this is also similar as the sum function but the Var name should be added to the parameter using the .(Var name of the values to be added) and console.log the output. the main part is keeping the initial value in the end of the function.

The last example gives the Number Of times the same amount is repeated in the array And increments the number.

This is similar to the For loop but for loop takes many lines of code and reduce function reduces the lines of code and do multiple actions in one function.

Output Of the following code:

Expected Output

--

--

Jagadhiswaran D
Jagadhiswaran D

Written by Jagadhiswaran D

Front-end Developer | JavaScript Developer | Web Developer | Software Engineer | Blockchain Ethusiast | Web3.js | Ethereum |