Arrays + functions: reduce()

Calling the reduce() method on an array allows us to transform that array to anything else.

Like a number, or a boolean.

The reduce() function wants 2 parameters: a function, and a value, which we call accumulator.

Here’s an example.

const a = [1, 2, 3, 4]

const result = a.reduce((accumulator, item, index, array) => {
  return accumulator * item
}, 1)

reduce() does 4 iterations on the array.

Notice the accumulator value received by the function. Its initial value is the second parameter of reduce(), which is in this case 1.

In the first iteration, accumulator is 1 and it returns 1 * 1 = 1.

In the second iteration, accumulator is 1 and it returns 1 * 2 = 2.

In the third iteration, accumulator is 2 and it returns 2 * 3 = 6.

In the fourth iteration, accumulator is 6 and it returns 6 * 4 = 24.

The value or result is 24.

Let’s do another example. We sum the numbers in an array:

const a = [1, 2, 3, 4]
const result = a.reduce((accumulator, item) => accumulator + item)

Notice I didn’t pass the initial value of the accumulator. When this happens, reduce() uses the default, which is 0

The value of result is 10.

Here’s an example that works with an array of objects.

We sum the values of all the content.value property contained in this array:

const items = [
  { name: 'a', content: { value: 1 }},
  { name: 'b', content: { value: 2 }},
  { name: 'c', content: { value: 3 }}
]

The code can written as

const count = items.reduce((accumulator, item) => accumulator + item.content.value, 0)

Which is equivalent to using this loop:

let count = 0
for (const item of items) {
  count += item.content.value
}

Lessons in this unit:

0: Introduction
1: map()
2: filter()
3: ▶︎ reduce()
4: sort()
5: find() and findIndex()
6: forEach()