Table of contents
Array.reduce() has always boggled the minds of young JavaScript learners as it is composed of many parameters. However , by the time you'll finish this guide , you'll have a clear concept of what and how does this method works.
It's time to reduce !
.Reduce()
This method simply put it , brings down an array to a single value.Below is a basic example of how it works :
const arr = [1,4,6]
const Sum = arr.reduce((accumulator,currentValue,index,array)=>{
return accumulator += currentValue
},0)
console.log(Sum) // Output 11
Let's break it down . Firstly we assign an array over which we'll loop and then assign the method to the Sum
variable .
The method takes in two values , a callback function and an initial value. The callback function will be looped by the length of the array and takes in four parameters in order . The accumulator is the total value in which you're adding the current value , thus you also return it in the end and that's your final value . Think of it as the variable Sum
to which you are adding numbers. Similarly the accumulator is the total
value here . The currentValue is self-explanatory , it is the current value which is selected from the array . The index provides the current index which is being accessed. Optionally, .reduce() provides you with a copy of the array as the fourth parameter too.
We can also further simplify the method by enclosing the callback in its own function :
function AddNumbers(accumulator,currentValue,index,array){
return accumulator += currentValue
}
const arr = [1,4,6]
const Sum = arr.reduce(AddNumbers,0)
console.log(Sum) // Output 11
.Reduce() mistakes
Often new JS devs forget placing the
return
statement , thus the accumulated value is not returned and rather is undefined.The type of the initial value is also very important . You wouldn't want to set an Integer value to a String.
Wrapping up , now you should be able to use this method just like you would with Array.map or Array.forEach.
Thanks for reading.
Happy Coding ๐ฉโ๐ป !