javascript - Loop through array of objects and return sum of each total values by object element id -
i'm calculating taxes complicate invoicing approach. can't explain whole process if have questions answer best can.
i come array of objects in js:
[ {row_id: "20003859", expense_id: "429", tax_select: "tax1", tax_id: "1", tax_name: "gst 5%", tax_no: "", tax_value: "13.23"}, {row_id: "20003859", expense_id: "429", tax_select: "tax2", tax_id: "3", tax_name: "qst 9.975%", tax_no: "", tax_value: "26.38"}, {row_id: "20003840", expense_id: "409", tax_select: "tax1", tax_id: "1", tax_name: "gst 5%", tax_no: "", tax_value: "13.23"}, {row_id: "20003840", expense_id: "409", tax_select: "tax2", tax_id: "3", tax_name: "qst 9.975%", tax_no: "", tax_value: "26.38"}, {row_id: "20003870", expense_id: "419", tax_select: "tax1", tax_id: "2", tax_name: "hst 13%", tax_no: "", tax_value: "34.39"} ]
as can see have 3 tax_ids: 1, 2 , 3. can have many sake of simplicity put 3.
i need loop through array of objects , come array of objects having totals tax_id:
[ {tax_name: "gst 5%", total_tax: sum of tax_value tax_id = 1}, {tax_name: "qst 9.975%", total_tax: sum of tax_value tax_id = 3}, {tax_name: "hst 13%", sum of tax_value tax_id = 2} ]
after can loop through array , display totals of each tax, adding subtotal , display total invoice.
also, should sort them tax_select it's thing can live with.
i have tried to: selected_taxes first array of objects
(i = 0; < selected_taxes.length; i++){ var sum = 0; $.each( selected_taxes[i], function( tax_id, tax_value ) { sum += tax_value; }); console.log(sum); }
but no luck.
many or suggestions.
i think array.prototype.reduce
best bet this:
var totals = data.reduce(function(c,x){ if(!c[x.tax_id]) c[x.tax_id] = { tax_name: x.tax_name, tax_id: x.tax_id, total_tax: 0 }; c[x.tax_id].total_tax += number(x.tax_value); return c; }, {});
this approach generates object has, properties, tax id numbers. if want flat array that, can convert array after fact:
var totalsarray = []; for(var taxid in totals){ totalsarray.push(totals[taxid]): }
demonstration: http://jsfiddle.net/3jajc/1/
Comments
Post a Comment