hpxue13
hpxue13

Reputation: 69

ES6 reduce not workd as expected

I have an array of called orders,

const orders = [
  {
    name: 'iPhone 7',
    price: 7199,
    count: 2
  },
  {
    name: 'iPad 2',
    price: 3399,
    count: 1
  },
  {
    name: 'Macbook Pro',
    price: 19888,
    count: 1
  },
  {
    name: 'Kindle Osis',
    price: 2399,
    count: 2
  }
];

and I want to calculate the total price by summing each item's price times count up like this:

orders.reduce((e1, e2) => e1.price * e1.count + e2.price * e2.count);

but I got NaN instead of the total price, anyone can help? Thanks!

Upvotes: 2

Views: 409

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use with Array#reduce a start value for the sum and multiply only the actual values.

For the values, you could use a destructuring assignment, because you need only the two propeties price and count.

const orders = [{name: 'iPhone 7', price: 7199, count: 2}, {name: 'iPad 2', price: 3399, count: 1}, {name: 'Macbook Pro', price: 19888, count: 1}, {name: 'Kindle Osis', price: 2399, count: 2}],
    total = orders.reduce((sum, { price, count }) => sum + price * count, 0);
    //                                                                    ^

console.log(total);

Upvotes: 2

Michael Kurowski
Michael Kurowski

Reputation: 190

Use

orders.reduce((accumulator, order) => accumulator + order.price * order.count, 0);

I think that you get the idea of reduce wrong. The first argument is an accumulator (the result of all previous of reduce's iterations) so there is no need to multiply it by anything in your case. You just calculate the price of the current order and add it to the accumulator.

The 0 is an initial value for the accumulator to use during first iteration.

Upvotes: 0

Bergi
Bergi

Reputation: 664375

You

  • forgot to pass 0 as the initial value of a sum
  • did not consider that the first argument of the callback is the numeric result from the previous call, not an array element with properties.

So use

orders.reduce((sum, el) => sum + el.price * el.count, 0);

Upvotes: 6

Related Questions