In this post, I would like to explain how the reduce() method works and how we can use it.
In JavaScript, the reduce() method is a built-in function of the Array object that applies a function to the elements of an array cumulatively, until it gets a single value.
If you need to reduce a list to a single value, reduce()
method will be your best friend because it is a great tool to create a single summary value, such as calculating the total price of a shopping cart.
Let's examine it with an example.
const items = [
{
name: 'Amazon Fresh Bagels',
price: 3.99,
amount: 1
},
{
name: 'Amazon Fresh Cream Cheese',
price: 2.70,
amount: 1
},
{
name: 'Amazon Fresh Ground Turkey',
price: 5.99,
amount: 1
},
{
name: 'Amazon Fresh Whole Milk, 1 Gallon',
price: 2.99,
amount: 1
}
]
We can reduce array of items
into a single value: the total price. Our function ShoppingCardTotal()
will look like this:
function shoppingCardTotal(items) {
let totalPrice = 0;
for (const item of items) {
totalPrice += item.price;
};
return totalPrice;
}
console.log(shoppingCardTotal(items));
// LOG = 15.67
What happened here in our code?
We have an array of objects called items
that represents a shopping cart with a list of products; each has a name, price, and amount.
The shoppingCardTotal()
function takes the items array as an argument and calculates the total price of the items in the shopping cart using a for loop. Let's analyze our function in more detail:
function shoppingCardTotal(items) {
let totalPrice = 0;
for (const item of items) {
totalPrice += item.price;
};
return totalPrice;
}
First, our function initializes the totalPrice variable to 0.
The totalPrice
variable is set (initialized) to 0 to start with an empty sum because this variable serves as an accumulator to keep track of the cumulative sum of the prices as the shoppingCardTotal() function loops through each item in the items array. By starting with an empty sum, the totalPrice variable can be incremented with the price of each item in the items array, resulting in an accurate calculation of the total price.
Then, it loops through each item object in the items array using a for...of loop[1].
On each iteration of the loop, it adds the price property of the current item to the totalPrice variable using the += operator.
Finally, it returns the totalPrice variable, which represents the total cost of all the items in the shopping cart.
Let's change the amount of some items.
const items = [
{
name: 'Amazon Fresh Bagels',
price: 3.99,
amount: 1
},
{
name: 'Amazon Fresh Cream Cheese',
price: 2.70,
amount: 2
},
{
name: 'Amazon Fresh Ground Turkey',
price: 5.99,
amount: 3
},
{
name: 'Amazon Fresh Whole Milk, 1 Gallon',
price: 2.99,
amount: 1
}
];
We need to update our function, shoppingCardTotal()
, accordingly.
function shoppingCardTotal(items) {
let totalPrice = 0;
for (const item of items) {
totalPrice += item.price * item.amount;
};
return totalPrice;
}
console.log(shoppingCardTotal(items));
// LOG = 30.35
In our updated function, the totalPrice
variable is still initialized to 0. However, instead of simply adding the price of each item to the totalPrice, we multiply the price by the amount of each item before adding it to the totalPrice. By doing this, we ensure that the total price of the shopping cart includes the quantity of each product.
So far, we wrote a basic function in which we manually added the prices together to get the logic of how .reduce()
works. A more abstract and reusable solution can be achieved by creating a generalized function that takes two additional parameters other then our array items: an initial value and a callback function.
function shoppingCardTotal(items, multiplyAndSum, init) {
let totalPrice = init;
for (const item of items) {
totalPrice = multiplyAndSum(totalPrice, item);
};
return totalPrice;
}
function multiplyAndSum(total, item) {
return total + (item.price * item.amount);
}
console.log(shoppingCardTotal(items, multiplyAndSum, 0));
// LOG = 30.35
Our updated function takes three parameters: the shopping cart items, an initial value (init) for the total price calculation, and a callback function multiplyAndSum
to calculate the total price. We initialize totalPrice to the init value, loop through each item and update the totalPrice using the callback function. The function returns the final totalPrice value as the total price of all the items in the shopping cart.
function shoppingCardTotal(items, multiplyAndSum, init) {
return items.reduce((total, item) => multiplyAndSum(total, item), init);
}
function multiplyAndSum(total, item) {
return total + (item.price * item.amount);
}
console.log(shoppingCardTotal(items, multiplyAndSum, 0));
// LOG = 30.35
In this last version, the shoppingCardTotal function uses the .reduce() method on the items array. It starts with an initial value of init and applies the multiplyAndSum function for each item in the array, accumulating the result.
The multiplyAndSum function remains the same, performing the multiplication and addition to calculate the subtotal for each item.
The result is then directly returned by the .reduce() method, eliminating the need for a separate totalPrice variable.
Overall, with reduce() our code is utilized and became more concise.
Using the reduce() method with an init and a callback function is advantageous in several ways:
Reusability: The reduce() method can be used for a wide range of reduce operations, not just for calculating the total price of items in a shopping cart. By abstracting the reduce functionality into a separate callback function, it becomes easier to reuse this code in other parts of your application or for other reduce operations.
Flexibility: By providing an initial value, we have greater control over the starting point to keep track of the cumulative sum. This means you can use the same reduce function for different types of data sets or with different starting values without having to write separate functions for each scenario.
Code readability: Using the reduce() method can make the code more readable and easier to understand, especially for developers familiar with this method. It can also make the code more concise compared to using a for loop or other iteration methods.
Please check other sources for more information[2], [3].
Keep coding and have a great day!
Bouquet
References:
[1] Learn more about for ... of
[2] Array.prototype.reduce()
[3] JavaScript Array reduce()
Top comments (0)