Master programming syntax, solve interactive challenges & run live code in Syntaxis Explore Arena →
Reference / JavaScript

Array.prototype.reduce()

Executes a user-supplied reducer callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.

Syntax
reduce(callbackFn: (accumulator: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue?: U): U

Parameters

NameTypeDescription
callbackFnFunctionReducer function with signature (accumulator, currentValue, index, array).
initialValueUValue to use as the first argument to the first call of callbackFn.

Examples

Grouping by category
const inventory = [
  { name: 'asparagus', type: 'vegetables' },
  { name: 'bananas', type: 'fruit' },
  { name: 'goat', type: 'meat' }
];
const grouped = inventory.reduce((acc, item) => {
  (acc[item.type] = acc[item.type] || []).push(item);
  return acc;
}, {});
console.log(grouped);
Always provide an explicit initialValue to avoid runtime TypeErrors on empty arrays.