Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – use redcuce to calculate total cost in array

I have an array with items. Each of these items have the following values

invoice_rows: [
  { item: '', qty: '', price: '' }
],

For each invoice item there is a row added to the array but I want to get the total cost of all these items. So let’s do some math, I have the following array with data

invoice_rows: [
  { item: 'item1', qty: '4', price: '10' }
  { item: 'item2', qty: '2', price: '10' }
  { item: 'item3', qty: '5', price: '5' }
],

The total cost should be the sum of the qty * price for each row. Making the total 40 + 20 + 25 = 85. How can I do this with the reduce method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Simply calculate qty * price for both items, then add them:

const invoice_rows = [
  { item: 'item1', qty: '4', price: '10' }
  { item: 'item2', qty: '2', price: '10' }
  { item: 'item3', qty: '5', price: '5' }
];
const total = invoice_rows.reduce((a, b) => a.qty * a.price + b.qty * b.price);

using map for this might be slightly more readable, first calculating qty * price for all items, then adding them:

const total = invoice_rows.map(item => item.qty * item.price).reduce((a, b) => a + b);

note that JS will implicitly cast '4' * '10' to the the number 40.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading