There are two different ways you can use the method in JavaScript.
1) Using a user-defined reducer function or a callback function
2) Using Arrow function
Let us see some examples first to understand how the reduce() method actually works.
1) reduce() Method using Arrow function
Here I am using the arrow function to calculate the sum of values (integer values) in an array using the reduce() method.
<script> let calc = () => { const arr = [5, 4, 3, 2, 1]; const result = arr.reduce((prev, cur) => prev + cur); document.write (result); document.write ('<br >' + arr); } calc(); </script>
In the above example, I have an array of 5 values or a series of numbers. It calculates the sum of all the numbers in the array and returns a single value, 15.
The reduce method works like a for loop. It runs through each element (number in this case), adds the current number to the previous total and finally returns the result (a single number).
Note: Did you notice the second output from the above example. document.write ('<br >' + arr);
The second result shows the original array (after the sum result), which I have declared in the beginning. What I-am trying the show in the example is that the reduce() method does not change the original array. The array values and its sequence remains the same.
2) reduce() Method using a callback function
We can execute the above example using a callback function. That is, by providing the reduce() method with callback function as parameter.
<script> let calc = () => { const arr = [1, 2, 3, 4, 5]; const result = arr.reduce(sum); document.write (result); } let sum = (prev, cur) => { return prev + cur; } calc(); </script>
The result or the output is the same as in the first example. However, in this example, the reduce() method has callback function named sum.
You must see the syntax now. There’s more to it.
Syntax array.reduce() Method
array.reduce(function (previousValue, currentValue, currentIndex, arr), initialValue)
The reduce() method takes few parameters. Some are required and some are optional.
function: It’s the callback function that is called for every element. This is required.
previousValue: The previously returned value. This is required.
Note: To understand this parameter, run the sum() function in the 2nd example (see above) with the console.log() method. Like this…
let sum = (prev, cur) => {
console.log(prev);
return prev + cur;
}
currentValue: The value of current element. This is also required.
Note: To understand this parameter, run the sum() function in the 2nd example (see above) with the console.log() method. Like this…
let sum = (prev, cur) => {
console.log(cur);
return prev + cur;
}
currentIndex: The index (or position in the array) of the current value or element. This is optional.
For example,
let calc = () => { const arr = [1, 2, 3, 4, 5]; const result = arr.reduce(sum, 0); document.write (result); } let sum = (prev, cur, indx) => { console.log(indx); // See the output in your browsers console window. return prev + cur; } calc();
When you run the above code, see the output in your browser’s console window also. You will see the current index of each element. It will start from index 1. However, if you have provided an “initial value” (see the 2nd parameter inside reduce(sum, 0), which is a 0) to the method, it will start from index 0.
array: The array from which the current element is processed. This is optional.
See this example,
let calc = () => { const arr = [1, 2, 3, 4, 5]; const result = arr.reduce(sum); document.write (result); } let sum = (prev, cur, indx, arr) => { console.log(arr); return prev + cur; } calc();
initialValue: A value passed to the callback function, indicates the initial value. This is optional.
See this example. I’ll pass an initial value to the callback function and it will add up to the final output.
let calc = () => { const arr = [1, 2, 3, 4, 5]; const result = arr.reduce(sum, 10); document.write (result); } let sum = (prev, cur) => { return prev + cur; } calc();
The result would have been 15 (the sum of all the array values). However, I have passed an initialValue (10) to the method arr.reduce(sum, 10);. So, the output would be 15 + 10 = 25.
The reduce() method may look a little complicated in the beginning. However, after few examples, you will feel comfortable with it. Its very useful.
You can use the reduce() method to do more calculations like subtraction, do some Math equations and more.
Subtract Array values using reduce() Method
<script> let calc = () => { const arr = [18, 9, -12, 31, 2]; const result = arr.reduce(subtract, 0); document.write (result); } let subtract = (prev, cur) => { return prev - cur; } calc(); </script>
Using reduce() with map() Method
Here’s another example. You can use the reduce() method with other methods like the map().
In this next example, I am using a JSON array. The array has two different types of values: subject and marks.
I’ll filter the marks first, using JavaScript array.map() method and then calculate the total marks.
This is interesting.
<script> let cal_total_marks = () => { const arr = [ {"Subject": "Math", "Marks": 87 }, {"Subject": "Science", "Marks": 91 }, {"Subject": "Sanskrit", "Marks": 83 } ]; const arrMarks = arr.map(students => students.Marks); const result = arrMarks.reduce(sum, 0); document.write (result); } let sum = (prev, cur) => { return prev + cur; } cal_total_marks(); </script>
Remember: The array.reduce() method does not alter the original array.