Introduction
As the title suggest we are going to discuss one of the most widely used array methods : reduce
The word itself describes that it reduces the input value to single output value. Let us see how it works!
- It iterates over each element in an array from left to right
It accepts a callback function which has following parameters accumulator , currentvalue , index ,array and an optional intial value. ( although it is optional but it's a best practice to use it )
Syntax :
reduce(function(accumulator, currentValue, index, array) {
/* function-body */
}, initialValue)
accumulator (a) - it is the return value in last iteration or initial value
currentvalue (c) - it is the value of the current element in the current ongoing iteration
index - it is the index of the current iteration
array - it is an input array on which we are providing applying the reduce function
initialValue - it is the starting value that is to be returned to the accumulator in the very first iteration
Now enough theory let us take a look an example. In this example we are going to calculate the total of all the numbers given in an array of numbers.
let arr = [ 1, 2 ,3,4,5,6,7,8,9,10];
const sum = arr.reduce((accumulator,currentvalue) => accumulator + currentvalue,0);
console.log("Sum : ",sum);
In the above example on the very first iteration, the value of accumulator is the initial value i.e 0 and current value is 1.
Thus it returns 0 plus 1 resulting 1 and accumulator value becomes 1. ( as we have provided addition logic )
Now in the next iteration, the value of accumulator is 1 and currentvalue is 2 so the next value of accumulator results into their addition as 3
This goes on till last iteration and the accumulator values is returned.
Take a note that we can provide any logic as per our need inside the function body. And also, we can provide any initial value.
Some of the practical use cases where we can use reduce function are :
- create string from an array of characters.
- Find max. value in a given array of numbers
- Find the array of names for the given array of employees whose age is > 40
- Find the frequency of same aged users from given array.
Thank you for stopping by. If you find it useful consider sharing it. You can connect with me here : linkedin
Top comments (2)
Nice one, I loved the article. I found the pink background a bit flashy (If you want to change it, I use carbon.now.sh/ on the settings you can change the background color or make it transparent). Keep up the good work ;)
Thanks for your feedback fam 😀.I will note that one 👍.