JavaScript reduce()
The reduce()
method in JavaScript reduces an array to a single value by iteratively applying a function to each element of the array until the final result is obtained.
Syntax
array.reduce(function(accumulator, currentValue, index, arr), initialValue)
function(accumulator, currentValue, index, arr)
: The function to be executed on each element of the array. It takes four arguments:accumulator
: the result of the previous iteration (orinitialValue
for the first iteration)currentValue
: the current element being processedindex
(optional): the index of the current element being processedarr
(optional): the array thatreduce()
was called on
initialValue
(optional): the initial value to be used as the first argument (accumulator
) when the function is executed for the first time
Example
Here is an example that uses reduce()
to find the sum of an array of numbers:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 15
Output
The output of the above example will be 15
, which is the sum of the numbers in the array.