JavaScript Reduce Method Explained

JavaScript Reduce Method Explained

ยท

2 min read

Array Reduce method:

Now we are going to learn about the reduce()method and

Do check my previous blog where I explained the Filter() method ( JavaScript Filter Method )

The reduce method just boils down the entire array into one single output value.

Here is a example,

const arr = [43,54,84,93]
const reducedValue = arr.reduce((acc, curr)=>{
     return acc + curr
},0);

Here we have two parameters,

acc - It is just a snowball that accumulates the value at the end , curr - It is just the current value and 0 defined, this is the initalValue at which we want the reduce method to start.

The reduce method takes up four arguments,

Accumulator: It is the accumulator value

currentValue: It is the required current value

IndexValue: The index of the current element being processed in the array.

ArrayValue: It is just the reduce() called upon

Here is a another example ,

const movements = [2,3,4,5,6,7,8]

 const balance = movements.reduce(function (acc, cur, i, arr) {
   console.log(`Iteration ${i}: ${acc}`);
  return acc + cur;
}, 0);
/*
The Output :

Iteration 0: 0 
Iteration 1: 2 
Iteration 2: 5 
Iteration 3: 9 
Iteration 4: 14 
Iteration 5: 20 
Iteration 6: 27
*/

Conclusion:

At first sight, the reduce looks more complex than other JavaScript Array Iteration Methods like map and filter, but once the syntax, core concepts and use-cases are understood it can be another powerful tool for JavaScript developers.

What is your thought about the reduce method ? Comment it below ๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป

ย