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

前端 未结 4 1487
南方客
南方客 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 22:35

    I think Array.prototype.reduce will be your best bet for 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 an object that has, as its properties, the tax ID numbers. If you really want a flat array from that, you can convert that into an array after the fact:

    var totalsArray = [];
    for(var taxId in totals){
        totalsArray.push(totals[taxId]):
    }
    

    Demonstration: http://jsfiddle.net/3jaJC/1/

    0 讨论(0)
  • 2021-01-14 22:48

    Use the reduce method:

    selected_taxes.reduce(function (p, c) {
        if (p[c["tax_id"]]) {
            p[c["tax_id"]]["total_tax"] += +c["tax_value"];
        } else {
            p[c["tax_id"]] = {
                "tax_name": c["tax_name"],
                "total_tax": +c["tax_value"]
            }
        }
        return p;
    }, {});
    

    This returns a new object containing the desired data:

    {
        "1": {
            "tax_name": "GST 5%",
            "total_tax": 26.46
        },
        "2": {
            "tax_name": "HST 13%",
            "total_tax": 34.39
        },
        "3": {
            "tax_name": "QST 9.975%",
            "total_tax": 52.76
        }
    }
    

    DEMO

    0 讨论(0)
  • 2021-01-14 22:55

    When you're looping over the objects, see what taxId it is and generate a sum for each different taxId.

    var sums = {}, obj, i;
    for (i = 0; i < selected_taxes.length; i++){
        obj = selected_taxes[i];
        if (!sums[obj.tax_id]) {
            sums[obj.tax_id] = 0;
        }
        sums[obj.tax_id] += +obj.tax_value;
    }
    console.log(sums); //{ 1:26.46, 2:34.39, 3: 52.76}
    

    http://jsfiddle.net/4X6Wb/

    0 讨论(0)
  • 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].

    0 讨论(0)
提交回复
热议问题