The reduce() method in JavaScript is used to reduce the array to a single value. It executes a provided function for each value of the array (from left to right) and accumulates the result. The reduce() method takes two arguments: the reducer function and an optional initial value.
Syntax
array.reduce(callback(accumulator, currentValue, index, array), initialValue);
Parameters
Parameters | Descriptions |
---|---|
callback() | A function to execute on each element in the array, taking four arguments: accumulator, currentValue, index, and array. |
accumulator | The accumulator accumulates the callback’s return values. It is the accumulated value previously returned in the last invocation of the callback, or initialValue if supplied. |
currentValue | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array reduce() was called upon. |
initialValue (Optional) | A value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue. |
Return Value
Return Type | Description |
---|---|
Any | The value that results from the reduction. |
Example 1: Summing Array Values
This code demonstrates how to use the reduce()
method to calculate the sum of values in an array.
let Arr = [1, 2, 3, 4, 5]; let sum = Arr.reduce( (accumulator, currentValue) => accumulator + currentValue); console.log(sum);
Output:
15
Example 2: Flattening an Array of Arrays
The reduce()
method can also be used to flatten an array of arrays.
let Arr = [[1, 2], [3, 4], [5, 6]]; let flattened = Arr.reduce( (accumulator, currentValue) => accumulator.concat(currentValue)); console.log(flattened);
Output:
[1, 2, 3, 4, 5, 6]
Example 3: Using reduce() with an Initial Value
You can provide an initial value to reduce()
as the second argument.
let Arr = [1, 2, 3, 4, 5]; let sum = Arr.reduce( (accumulator, currentValue) => accumulator + currentValue, 10); console.log(sum);
Output:
25
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
3 | 12 | 3 | 10.5 | 4 |