Tengo una matriz con artículos. Cada uno de estos elementos tiene los siguientes valores
invoice_rows: [ { item: '', qty: '', price: '' } ],Para cada elemento de la factura, se agrega una fila a la matriz, pero quiero obtener el costo total de todos estos elementos. Así que hagamos algunas matemáticas, tengo la siguiente matriz con datos
invoice_rows: [ { item: 'item1', qty: '4', price: '10' } { item: 'item2', qty: '2', price: '10' } { item: 'item3', qty: '5', price: '5' } ],El costo total debe ser la suma de la cantidad * el precio de cada fila. Haciendo el total 40 + 20 + 25 = 85. ¿Cómo puedo hacer esto con el método de reducción?
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);Dado
const invoice_rows = [ { item: 'item1', qty: '4', price: '10' } { item: 'item2', qty: '2', price: '10' } { item: 'item3', qty: '5', price: '5' } ]; simplemente calcule primero qty * price usando el map para todos los artículos, luego agregue los subtotales:
const total = invoice_rows.map(item => item.qty * item.price).reduce((a, b) => a + b, 0); tenga en cuenta que JS implícitamente lanzará '4' * '10' al número 40 .
Tu puedes hacer:
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)