How to reduce an array to just one value?

const numbers = [1, -1, 2, 42]
const reducer = (accumulator, currentValue) => accumulator + currentValue

// returns 44

// initial value is 2, returns 46
numbers.reduce(reducer, 2)

April 12th, 2020

# reduce() - Reduce an array to one value

Add to bookmarks

reduce() can be used to reduce an array of multiple elements to just one value. This can be coming handy for instance when calculating the sum of all elements of an array.

This is achieved by applying a reducer function as first parameter and an optional initial value as second parameter: reduce(reducer()[, initialValue]).

reduce() returns one value and doesn't mutate the original array.