61. Array Aggregation: The .reduce() Method
.reduce() is the most versatile array method. It executes a callback function on every element of the array, resulting in a single output value (the 'accumulator'). This is useful for summarizing, counting, or summing data.
Syntax
javascript array.reduce(callback(accumulator, currentValue), initialValue);
- Accumulator: The running total (the result of the previous calculation).
- Current Value: The element currently being processed.
- Initial Value: The starting value for the accumulator (optional, but highly recommended).
Example: Calculating a Total Sum
javascript const numbers = [10, 5, 2];
const sum = numbers.reduce((total, number) => {
console.log(Accumulator: ${total}, Current: ${number});
return total + number;
}, 0); // Start the total at 0
console.log('Final Sum:', sum); // Output: Final Sum: 17
Note: .reduce() can also be used to transform an array into an object, which we will cover in a more advanced lesson.