Introduction to Reduce method in JavaScript
In this tutorial, we will learn about how to use and when to use the Reduce method in JavaScript.
What is Reduce method?
The reduce() method reduces all array elements down to one single value
The return value of the function is stored in an accumulator(total/result).
Note: This method does not change the original array.
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
For Example,
Suppose we have an array as follows:
let arr = [44,54,25,56];
Now we want to count the total amount from the above array, we can do this using reduce method as follows:
let total = arr.reduce(function (acc, cur, i, arr) {
return acc + cur;
}, 0);
console.log(total);//179