DEV Community

Cover image for Learning the reduce function part 1
Adam Preece
Adam Preece

Posted on • Updated on

Learning the reduce function part 1

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)

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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('------')
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Yes!

Challenges!

  1. Use this reducer and caluclate an average(mean).

  2. See if you can rewrite all the above into one line of code, maybe with an arrow function!

  3. 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)
Enter fullscreen mode Exit fullscreen mode
const average = array.reduce(reducerTotal, 0) / array.length

function reducerTotal(previousValue, currentValue) {
  return previousValue + currentValue
}

console.log(average)

Enter fullscreen mode Exit fullscreen mode
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)

Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

initalValue can also be omitted - if it is omitted, it will automatically be set to the first value of the array and the reduce will proceed from the next item. This can be advantageous for performance

Collapse
 
quality_pre profile image
Adam Preece

Thank you for posting that useful tip!

Collapse
 
soufiane profile image
Soufiane

if you can explain why we put 0 in the initialValue