The reduce()
method in JavaScript takes an array and reduces it to a single value. It does this by repeatedly applying a function to each item in the array, accumulating the result each time. The final value can be anything—like a sum of numbers, a new array, or an object.
In the first iteration of reduce()
, if no initial value is provided, the first element of the array automatically becomes the initial value, and the process starts with the second element. However, if you do supply an initial value, the process begins from the first element, using that initial value in the first callback.
Syntax
array.reduce(callback(accumulator, currentValue, index, array), initialValue)
Parameters
callback
(Required):- A function to execute on each element of the array. It takes four arguments:
accumulator
: The value returned from the previous iteration, or the initial value if supplied.currentValue
: The current element in the array being processed.index
: (Optional) The index of the current element being processed. It starts at0
if the initial value is provided, or1
if no initial value is supplied.array
: (Optional) The original array upon whichreduce()
was called.
- A function to execute on each element of the array. It takes four arguments:
initialValue
(Optional):- The value to use as the starting point for the accumulator. If this is not provided, the first element of the array is used as the initial accumulator value, and the iteration starts from the second element.
Return Value
The reduce() method returns the accumulated result from the final execution of the callback function.
How the reduce()
Method Works
The reduce()
method can sometimes seem intimidating, especially when you first encounter it. To fully understand its power, let’s break down how it works step-by-step with a detailed example.
Example – Calculate the Total Price of Items in a Shopping Cart
const cart = [
{ product: 'Phone', price: 500 },
{ product: 'Screen Protector', price: 10 },
{ product: 'Memory Card', price: 20 }
];
const totalPrice = cart.reduce((accumulator, currentItem) => {
return accumulator + currentItem.price;
}, 0);
console.log(totalPrice); // Output: 530
Step-by-Step Breakdown of reduce()
1. Initial Setup
In this example, we have an array called cart
that contains objects. Each object represents a product with a name (product
) and a price (price
). We want to calculate the total price of all the products in the cart using reduce()
.
The reduce()
method takes two arguments:
- A callback function that will be executed on each element.
- An initial value (in this case,
0
), which is the starting value for theaccumulator
.
2. Iteration 1 (Processing the First Element)
- Accumulator: The
accumulator
starts with the value of the initial value, which is 0 in this case. - Current Item: The first item in the array is
{ product: 'Phone', price: 500 }
.
The reduce()
function now performs the first iteration.
accumulator = 0;
currentItem = { product: 'Phone', price: 500 };
accumulator + currentItem.price;
// 0 + 500 = 500
After this iteration, the accumulator
becomes 500.
3. Iteration 2 (Processing the Second Element)
In the second iteration:
- Accumulator: The value of the accumulator is now 500 (the result from the first iteration).
- Current Item: The second item is
{ product: 'Screen Protector', price: 10 }
.
The reduce()
function performs the next operation.
accumulator = 500;
currentItem = { product: 'Screen Protector', price: 10 };
accumulator + currentItem.price;
// 500 + 10 = 510
After this iteration, the accumulator
is updated to 510.
4. Iteration 3 (Processing the Third Element)
In the third iteration:
- Accumulator: The accumulator is now 510 (result from the second iteration).
- Current Item: The third item is
{ product: 'Memory Card', price: 20 }
.
The reduce()
function performs.
accumulator = 510;
currentItem = { product: 'Memory Card', price: 20 };
accumulator + currentItem.price;
// 510 + 20 = 530
After the final iteration, the accumulator
is updated to 530, which represents the total price of all the items in the cart.
5. Final Output (console log)
After all the iterations are complete, the final value of the accumulator
(which is 530) is returned by the reduce()
method, and that’s what gets printed out.
console.log(totalPrice); // Output: 530