Hey there, friend!
Welcome to our tutorial on Array Functions - reduce! Today, we're going to calculate the total value of items in a shopping cart using this powerful function.
Task: Calculate the total value of items in a shopping cart using the reduce function.
Step 1: Create an array of items
Open your index.js file and create an array of items in your shopping cart. Each item should have a name and a price property.
const cart = [ { name: "Apple", price: 1.0 }, { name: "Banana", price: 0.5 }, { name: "Orange", price: 1.5 }, { name: "Mango", price: 2.0 },]
Step 2: Define the total variable and initialize it to 0
Create a total variable and initialize it to 0. This variable will store the total value of items in the cart.
let total = 0
Step 3: Use the reduce function
Now, use the reduce function to calculate the total value of items in the cart. The reduce function takes a callback function as an argument, which is called for each element in the array.
cart.reduce((accumulator, currentValue) => { return accumulator + currentValue.price}, 0)
Here, accumulator is the initial value (0) and currentValue is each item in the cart array. We add the price of each item to the accumulator and return the result.
Step 4: Assign the result to the total variable
Assign the result of the reduce function to the total variable.
total = cart.reduce((accumulator, currentValue) => { return accumulator + currentValue.price}, 0)
Step 5: Log the total value to the console
Use the console.log function to print the total value to the console.
console.log(`Total value of items in the cart: $${total.toFixed(2)}`)
Run the code!
Click the "Run" button to execute the code. You should see the total value of items in the cart printed to the console.
Output:
Total value of items in the cart: $5.00
Congratulations! You've successfully calculated the total value of items in the shopping cart using the reduce function.
What's next?
In the next tutorial, we'll explore another powerful array function - some. Stay tuned!
Tests