How does the Array.reduce() method work?
Asked on Aug 01, 2024
Answer
The Array.reduce() method in JavaScript is used to reduce an array to a single value by executing a reducer function on each element of the array, from left to right. Here's a simple example:
<!-- BEGIN COPY / PASTE -->
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // Output: 10
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- The "reduce" method takes two arguments: a reducer function and an initial value.
- The reducer function itself takes four arguments: "accumulator", "currentValue", "currentIndex", and "array" (only the first two are commonly used).
- In the example, the "accumulator" starts at 0 (the initial value) and accumulates the sum of the array elements.
- The final result of the "reduce" method is a single value, in this case, the sum of all numbers in the array.
Recommended Links:
← Back to All Questions