Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 406
hpxue13 Avatar asked Feb 14 '26 03:02

hpxue13


1 Answers

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);
like image 145
Bergi Avatar answered Feb 16 '26 17:02

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!