Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.reduce

Reduces an array to a single value.

Available since: ES5

Syntax

array.reduce(callbackFn, initialValue)

Parameters

ParameterTypeDescription
callbackFnFunctionA function that receives the accumulated value and the next element and returns the new accumulated value.
initialValueanyThe initial accumulated value.

Return value

anyThe final accumulated value.

Examples

Sum of numbers:

console.log([1, 2, 3, 4].reduce((sum, n) => sum + n, 0));

Output:

10

Summing a property of objects:

const orders = [{ total: 100 }, { total: 250 }];
 
console.log(orders.reduce((sum, order) => sum + order.total, 0));

Output:

350

Notes

Always pass an initial value: without it, calling the method on an empty array throws an error.

See also

Related recipes

In the tutorial

  • map, filter and reduce — The three main array processing methods in JavaScript: transforming, selecting and reducing to a single value.

Thanks for reading!

Donate to the site — we work hard for you.