Definition and Usage
The reduce()
function for arrays iterates through an array using a callback function to repeatedly reduce its elements into a single value.
Features
- You write the logic to reduce the array elements into a single value inside a callback function.
- At each step, the reduced value is returned using the
return
keyword. - The returned value is then used as the accumulated value in the next iteration, continuing the reduction with the same logic.
- The original array remains unchanged, and the final result is the single value obtained from the repeated reduction.
This function is especially useful when you want to use the elements of an array to produce a single, specific value (or to perform a filtering operation).
Basic Example
The following example demonstrates a useful way to use the reduce()
function to sum all elements in a given array into a single value.
/**
* Example of using reduce()
* to sum all elements of an array and produce a single accumulated value
*/
// Array to apply reduce() on
const numbers = [1, 2, 3, 4, 5];
// Callback function written by the developer
function sum(total, number) {
// Add the previous accumulated value and the current element
return total + number;
}
// Apply the callback function to all elements and return the single result
const result = numbers.reduce(sum);
console.log(result); // Output: 15
Syntax
arr.reduce(callbackFn[, initialValue])
arr
is the array to which the reduce()
function is applied.
Parameters
callbackFn |
A callback function that processes each element of the array.
The callback function parameters: callbackFn(accumulator, currentValue[, currentIndex[, array]])
|
---|---|
initialValue |
Optional. The initial value to use as the first argument to the first call of the callbackFn .
If omitted, the first element of the array is used as the initial accumulator value. |
The first parameter, callbackFn
, can be written in several forms depending on the function syntax:
// Arrow function
reduce((accumulator) => { /* … */ })
reduce((accumulator[, currentValue]) => { /* … */ })
reduce((accumulator[, currentValue[, currentIndex[, array]]]) => { /* … */ })
// Callback function reference
reduce(callbackFn)
reduce(callbackFn[, initialValue])
// Inline callback function
reduce(function (accumulator) { /* … */ })
reduce(function (accumulator[, currentValue]) { /* … */ })
reduce(function (accumulator[, currentValue[, currentIndex[, array]]]) { /* … */ })
reduce(function (accumulator[, currentValue[, currentIndex[, array]]]) { /* … */ }[, initialValue])
Return Value
Returns the result of the reduction. If the array is empty and no initialValue
is provided, a TypeError is thrown.
How the Callback Function Works
callbackFn(accumulator, currentValue[, currentIndex[, array]])
reduce()
/**
* Callback Function
*
* The callback function can be a named function (user-defined) or an anonymous function.
* Naturally, you can also use an arrow function for the callback.
*/
/* Using a named function as a callback */
function callbackFn(accumulator, currentValue[, currentIndex[, array]]) { // Named function definition
// Logic to accumulate a single value: must return the updated result
}
arr.reduce(callbackFn); // Pass the named function directly as an argument
/* Using an anonymous function as a callback */
arr.reduce(function(accumulator, currentValue[, currentIndex[, array]]) {
// Logic to accumulate a single value: must return the updated result
});
The reduce()
function's callback is called for each element of the array, accumulating values from previous iterations. Here's a detailed explanation of how the callback function works:
- First iteration: When
reduce()
is called, theinitialValue
(if provided) and the first element of the array are passed to the callback function.accumulator
: Assigned the value ofinitialValue
.currentValue
: Assigned the value of the first element of the array.- The callback function is executed, using the previous result (
accumulator
) and the current element (currentValue
) to return a new value.
- From the second iteration onward: The
initialValue
is no longer used. Instead, the previous result (accumulator
) and the current element (currentValue
) are passed to the callback function.accumulator
: Assigned the value returned from the previous iteration.currentValue
: Assigned the value of the next array element.- The callback function is executed, using the previous result (
accumulator
) and the current element (currentValue
) to return a new value.
- Iteration continues: This process repeats until all elements of the array are processed.
- Final result returned: After all elements have been processed,
reduce()
returns the value from the last callback function execution as the final result.
Through this process, the reduce()
function iterates over the array, repeatedly calling the callback and accumulating results. Inside the callback function, you can perform any operations using the current element and the accumulated result from previous iterations.
Note: The currentIndex
and array
parameters are optional. They are only used when needed within the callback function.
Practical Examples
The reduce()
function is commonly used for examples like the ones below.
Summing All Elements of an Array
const numbers = [1, 2, 3, 4, 5];
const sum = (total, number) => {
return total + number;
}
const result = numbers.reduce(sum);
console.log(result); // Output: 15
Multiplying All Elements of an Array
const numbers = [2, 3, 4, 5];
const sum = (total, number) => {
return total * number;
}
const result = numbers.reduce(sum, 1);
console.log(result); // Output: 120
In the code above, the initial accumulated value is set to 1, and each element is multiplied to accumulate the result. Using 0 as the initial value would result in all values being multiplied to 0, so setting it to 1 is important.
Finding the Minimum Value in an Array
const numbers = [5, 3, 9, 2, 7];
const min = (min, item) => {
return (item < min) ? item : min;
}
const result = numbers.reduce(min, numbers[0]);
console.log(result); // Output: 2
Here, the initial accumulated value is set to the first element of the array (numbers[0]
), and the callback function selects the current element as the minimum if it is smaller than the accumulated value.
Finding the Maximum Value in an Array
const numbers = [5, 3, 9, 2, 7];
const max = (max, item) => {
return (item > max) ? item : max;
}
const result = numbers.reduce(max, numbers[0]);
console.log(result); // Output: 9
Similarly, the initial accumulated value is set to the first array element, and the callback function selects the current element as the maximum if it is greater than the accumulated value.
Specifications
Specification | |
---|---|
reduce()
|
ECMAScript Language Specification #sec-array.prototype.reduce |
Browser compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
reduce()
|
3 | 12 | 3 | 4 |