javascript / beginner
Snippet
Calculating Shopping Cart Totals Using Array Reduce
Aggregating data from an array of objects into a single numeric total is a standard JavaScript array operation. By leveraging the reduce method inside a Vue computed property, the cumulative monetary value is calculated deterministically and kept in sync with the array items.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
import { ref, computed } from 'vue';const cartItems = ref([{ id: 1, name: 'Keyboard', price: 79.99, quantity: 1 },{ id: 2, name: 'Mouse', price: 39.50, quantity: 2 }]);const totalPrice = computed(() => {return cartItems.value.reduce((accumulator, item) => {return accumulator + (item.price * item.quantity);}, 0);});
vue
Breakdown
1
const cartItems = ref([ ... ]);
Stores a reactive list of item objects, each containing price and quantity numeric properties.
2
const totalPrice = computed(() => {
Creates a computed property that automatically re-evaluates when cart items or quantities change.
3
return cartItems.value.reduce((accumulator, item) => {
Iterates over the array, passing the running total accumulator and the current item to the callback.
4
return accumulator + (item.price * item.quantity);
Multiplies item price by quantity and adds the subtotal to the accumulated sum.
5
}, 0);
Initializes the accumulator with an initial numeric value of zero.