sum of array with the save id javascript

Solutions on MaxInterview for sum of array with the save id javascript by the best coders in the world

showing results for - "sum of array with the save id javascript"
Rafael
22 Jul 2017
1var a = [];
2        a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
3        a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'20.00'});
4        a.push({taxid : 1, tax_name: 'VAT', tax_value:'25.00'});
5        a.push({taxid : 2, tax_name: 'Service Tax', tax_value:'75.00'});
6        
7//Sum up all the same taxid tax_value
8var temp = {};
9a.forEach(function(obj){
10   if(!temp[obj.taxid]){
11     temp[obj.taxid] = obj.tax_value;
12   } else {
13     temp[obj.taxid] = Number(temp[obj.taxid]) + Number(obj.tax_value);
14   }
15});
16
17//Format the data into desired output
18var result = [];
19for(var key in temp){
20  result.push({
21    taxid: key,
22    tax_value: temp[key]
23  })
24}
25
26console.log(result)