In JavaScript, the reduce()
function is used to iterate through an array and accumulate a single result (such as a value, object, or array) by applying a function to each element of the array.
The primary purpose of reduce()
is to transform an array into a single value or object based on some operation performed on each element. It takes a callback function as its argument and an optional initial value.
The callback function in reduce()
takes four parameters:
- Accumulator: The variable that accumulates the result.
- Current Value: The current element being processed in the array.
- Current Index: The index of the current element being processed.
-
Array:
The original array that
reduce()
was called upon.
The callback function can perform any operation using the accumulator and the current value, and it should return the updated accumulator. This updated accumulator is then used in the next iteration.
Here's a basic example that demonstrates the use of reduce()
to find the sum of all elements in an array:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output will be 15 (1 + 2 + 3 + 4 + 5)
In this example:
-
accumulator
starts at 0 (the initial value provided as the second argument toreduce()
). -
The callback function adds each
currentValue
to theaccumulator
. - The final result is the sum of all elements in the array.
reduce()
is versatile and can be used for various operations such as calculating totals, flattening arrays, filtering, mapping, and more, depending on the logic defined within the callback function.