The reduce() method in JavaScript is used to execute a reducer function on each element of an array, resulting in a single output value. It takes two parameters: a callback function and an optional initial value.
Syntax
array.reduce((accumulator, currentValue, currentIndex, array) => {
// logic to combine values
}, initialValue);
Parameters
- accumulator: 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.
- currentIndex (optional): The index of the current element being processed.
- array (optional): The array
reduce()was called upon.
Example
Here's a simple example that sums all the numbers in an array:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // Initial value is 0
console.log(sum); // Output: 15
In this example:
- The
reduce()method iterates over each number in thenumbersarray. - The
accumulatorstarts at0(the initial value) and adds eachcurrentValueto it. - The final result is the sum of all numbers in the array.
