Zach
Zach

Reputation: 11

Using reduce to sum the price of objects in an array

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

Answers (3)

djcaesar9114
djcaesar9114

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

Ninad Bondre
Ninad Bondre

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

Hien Nguyen
Hien Nguyen

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

Related Questions