I won't lie.
I struggle with reduce, even now!
But it is powerful and it is worth learning.
What is reduce?
function used on arrays/object
reduce will loop over every item
gives a single result
Let's start with a basic (and overly used!) usage:
Finding a total...
array = [3, 12, 14, 23, 2, 3, 2, 13, 0, 2, 234, 213]
const total = array.reduce((previousValue,currentValue,indexNumber,array)=> {
code here
},initialValue)
Reduce takes 4 arguments, for this example we will only need the first two. The initialValue will be zero.
const total = array.reduce((previousValue,currentValue)=>{
code here
},0)
Refactoring tip
To make it more easily readable I will make the 2 arguments into a callback function. This is sometimes called the 'reducer'
const total = array.reduce(reducerTotal, 0)
function reducerTotal(previousValue, currentValue) {
console.log('Previous Value:', previousValue)
console.log('CurrentValue:', currentValue)
console.log('------')
}
Have a look what happens, change the 0..what happens?
Currently it is correctly looping, but we are not totalling the numbers.
Whatever you return is what the previousValue is going to be.
That is why we got 'undefined' as there was no function return.
Try to return something silly like "I love Reduce" and study what now happens!
Now let us actually add, to create our total so..
const total = array.reduce(reducerTotal, 0)
function reducerTotal(previousValue, currentValue) {
return previousValue + currentValue
}
console.log(total)
Yes!
Challenges!
Use this reducer and caluclate an average(mean).
See if you can rewrite all the above into one line of code, maybe with an arrow function!
Create a new reducer, that takes a total amount of money say £1000 and your array are amounts of money that you spend. Reduce this to see how much you have left..
Scroll Down for answers(please try before!)
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
There may be other (and better ways!) Please share below!!
const oneLiner = array.reduce((prev, curr) => prev + curr)
console.log(oneLiner)
const average = array.reduce(reducerTotal, 0) / array.length
function reducerTotal(previousValue, currentValue) {
return previousValue + currentValue
}
console.log(average)
spendings = [3, 12, 14, 23, 2, 3, 2, 13, 0, 2, 234, 213]
const money = 1000
const howMuchDoIHaveLeft = spendings.reduce(reducerTotal, money)
function reducerTotal(previousValue, currentValue) {
return previousValue - currentValue
}
console.log(howMuchDoIHaveLeft)
You could also expand on this task, by adding a currency, rounding to 2 decimal places, even a warning check if your money goes below 0
Top comments (3)
initalValue
can also be omitted - if it is omitted, it will automatically be set to the first value of the array and thereduce
will proceed from the next item. This can be advantageous for performanceThank you for posting that useful tip!
if you can explain why we put 0 in the initialValue