How to get distinct values and sum the total on JSON using JS

How do you get the data from distinct values also sum the total values from the same unique row

Here is the JSON Data result

enter image description here

As you can see they have the same full name. How do you get the distinct value while sum the total priceGross.

The result should be returning eg. "Khalem Williams" and adding the total priceGross " 1200 + 1200 " = 2400

result return

FullName : "Khalem Williams" 
TotalPriceGross: "2400"

I'm getting the distinct values with the code below but I'm wondering how to sum the total priceGross while also getting the distinct values.

var countTotal = [];

$.each(data.aaData.data,function(index, value){
          if ($.inArray(value.invoiceToFullName, countTotal)==-1) {
                    countTotal.push(value.invoiceToFullName);
          }
});

Answers 1

  • Just created my own dummy data resembling yours hope you get the idea, if not you can paste your json and i can adjust my solution, was just lazy to recreate your json.

    Your problem seems to be a typical group by field from sql.

    Sample data:

       var resultsData = [{name: 'sipho', amount: 10}, {name: 'themba', amount: 30}, {name: 'sipho', amount: 60}, {name: 'naidoo', amount: 30}, {name: 'gupta', amount: 70}, {name: 'naidoo', amount: 10}];
    

    Get value of customer(field) you going to group by:

    var customers = $.unique(resultsData.map(function(value){return value.name}));
    

    Go through each customer and add to their sum:

    var desiredSummary = customers.map(function(customer){
        var sum =0; 
        $.each(test,function(index, value){sum+=(value.name==customer?value.amount:0)}); 
        return {customer: customer, sum: sum}
    });
    

    Hope it helps, Happy coding


Related Articles