'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?



Solution 1:[1]

Given

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

simply first calculate qty * price using map for all items, then add the subtotals:

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

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

Solution 2:[2]

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

const initialValue = 0;
const sumWithInitial = invoice_rows.reduce(
  (previousValue, currentValue) => previousValue + currentValue.qty*currentValue.price,
  initialValue
);

console.log(sumWithInitial);

Solution 3:[3]

You just start with an initial value of 0 and then reduce it as below...

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

const result = invoice_rows.reduce((previousValue, currentValue) => previousValue + (currentValue.qty * currentValue.price), 0);

console.log(result)

Hope this helps.

Solution 4:[4]

You can do:

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

const result = invoice_rows.reduce((a, { qty, price }) => a + qty * price, 0)

console.log(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ayush Gupta
Solution 3 OneJeet
Solution 4 Yosvel Quintero Arguelles