JavaScript Array Type

Reduce

As we write more and more code, we see some patterns emerge. We often end up defining a mutable accumulator variable with an initial value, iterating over an array and mutating the accumulator value based on the current value and the accumulator. This pattern is known as reduction, and can be done through the JavaScript method reduce.

reduce takes a mandatory callback function and an optional initial value. The callback function must take an accumulator parameter and a current value parameter and return the value the accumulator should be set to.

Code example: sum

const arr = [1, 2, 3, 4]
const sum = arr.reduce((acc, x) => acc + x, 0)
console.log(sum) // 10

A sum of numbers can be implemented easily with reduce by using an initial value of zero.

Code example: re-implementation of map

const myMap = (arr, fn) => arr.reduce(
(acc, x) => [...acc, fn(x)], []
)

The map method can be implemented using reduce by starting off with an empty array and applying the provided callback function to every element.

Code example: re-implementation of reduce

const myReduce = (arr, fn, initialValue) => {
let result = initialValue
arr.forEach(el => {
result = fn(result, el)
})
return result
}

The above re-implementation of reduce is not equivalent to the Array.prototype.reduce method, but it shows the basic concept.

Read more on MDN

Array.prototype.reduce()