A brief look at the reduce() function in JavaScript

The array method reduce can be a tricky one to grasp. Reduce takes some items, iterates over them and returns one value.

.reducer() takes two parameters:

  • Accumulator - fancy way of saying ‘previous state’ or ‘previous value’. Often passed in as acc for short.
  • Current Element - Current element being looped.

Let’s see

Let’s say we want to total up an array of numbers. The example below is the same as 1+2+3=6.

const myArray = [1,2,3]

const total = myArray.reduce((acc,num) => {
  return acc + num
},0)
// 6

Beginning state is declared as 0 as seen at the very bottom of the example.

The code did this:

  • 0+1=1
  • 1+2=3
  • 3+3=6

Another Example

Let’s create a shopping cart and create a function that works out the total cost using .reduce()

const cart = [
  { id: ‘apples’, price: 2.00 },
  { id: ‘oranges’, price: 3.00 },
  { id: ‘banannas’, price: 1.50 },
  { id: ‘avacado’, price: 4.20 }
]

const total = cart.reduce((acc,item) => {
  return acc + item.price
}, 0)
// 10.7

In the example we had an array of objects and wanted to total the price of each one. Just remember to add the 0 to set some initial value.