Loop through array of objects and return sum of each total values by object element id

前端 未结 4 1489
南方客
南方客 2021-01-14 22:03

I\'m calculating taxes for a very complicate invoicing approach. I can\'t explain the whole process but if you have questions I will answer as best as I can

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 23:01

    My solution using typed arrays:

    var sum_arr = new Float32Array(arr.length); for (var i = 0; i < arr.length; i++){ var tax_id = arr[i].tax_id; sum_arr[tax_id] += parseFloat(arr[i].tax_value); }

    jsfidle: http://jsfiddle.net/LJ7Nd/

    The idea: assume you have n tax_ids. Create an array of length n called sum_arr. Pull the tax_id at each iteration and increment that particular slot in the array by the corresponding tax_value. Then when you want the sum of all tax_values of tax_id = 1 you simply index sum_arr[1].

提交回复
热议问题