Reputation: 11
I have an array of objects that have a price property, and I'm trying to sum all the prices in the object. I think what's tripping me up is that it's an array of objects so I'm having a hard time accessing the price property.
Here's what's displaying in the console: 0[object Object][object Object][object Object][object Object][object Object][object Object][object Object]
Here's my code:
const items = [
{ name: 'Bike', price: 100 },
{ name: 'TV', price: 200 },
{ name: 'Album', price: 10 },
{ name: 'Book', price: 5 },
{ name: 'Phone', price: 500 },
{ name: 'Computer', price: 1000 },
{ name: 'Keyboard', price: 25 }
];
const totalPrice = items.reduce((total, curVal) => {
return total + curVal;
}, 0);
Upvotes: 0
Views: 934
Reputation: 2137
You were almost there!
const items = [
{ name: 'Bike', price: 100 },
{ name: 'TV', price: 200 },
{ name: 'Album', price: 10 },
{ name: 'Book', price: 5 },
{ name: 'Phone', price: 500 },
{ name: 'Computer', price: 1000 },
{ name: 'Keyboard', price: 25 }
];
const totalPrice = items.reduce((a, b)=> a + b.price,0);
console.log(totalPrice);
Upvotes: 1
Reputation: 75
const items = [
{ name: "Bike", price: 100 },
{ name: "TV", price: 200 },
{ name: "Album", price: 10 },
{ name: "Book", price: 5 },
{ name: "Phone", price: 500 },
{ name: "Computer", price: 1000 },
{ name: "Keyboard", price: 25 },
];
let sum = 0;
items.forEach((el) => {
sum += el.price;
});
console.log(sum);
explanation - we set sum initially to zero then we will loop through the array using foreach and access price property using el.price and calculate the sum
Upvotes: 0
Reputation: 18975
Because curVal is object, you need use price property by curVal.price
const items = [
{ name: 'Bike', price: 100 },
{ name: 'TV', price: 200 },
{ name: 'Album', price: 10 },
{ name: 'Book', price: 5 },
{ name: 'Phone', price: 500 },
{ name: 'Computer', price: 1000 },
{ name: 'Keyboard', price: 25 }
];
const totalPrice = items.reduce((total, curVal) => {
return total + curVal.price;
}, 0);
console.log(totalPrice);
Upvotes: 0