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): UParameters
| Name | Type | Description |
|---|---|---|
| callbackFn | Function | Reducer function with signature (accumulator, currentValue, index, array). |
| initialValue | U | Value 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.