Answers for "sum of array with the save id javascript"

0

sum of array with the save id javascript

var a = [];
        a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
        a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'20.00'});
        a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
        a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'75.00'});
        
//Sum up all the same taxid tax_value
var temp = {};
a.forEach(function(obj){
   if(!temp[obj.taxid]){
     temp[obj.taxid] = obj.tax_value;
   } else {
     temp[obj.taxid] = Number(temp[obj.taxid]) + Number(obj.tax_value);
   }
});

//Format the data into desired output
var result = [];
for(var key in temp){
  result.push({
    taxid: key,
    tax_value: temp[key]
  })
}

console.log(result)
Posted by: Guest on July-01-2021

Code answers related to "sum of array with the save id javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language