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
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);
}
});
I would honestly suggest converting your data to an object with names as keys (unique) and total gross prices as values:
{
"Khalem Williams": 2400,
"John Doe": 2100
}
However, I have included in the snippet below example code for how to convert your data to an array of objects as well. I used a combination of Object.keys
, Array#reduce
and Array#map
.
var data = {
aaData: {
data: [{
invoiceToFullName: "Khalem Williams",
priceGross: 1200
},
{
invoiceToFullName: "Khalem Williams",
priceGross: 1200
},
{
invoiceToFullName: "John Doe",
priceGross: 500
},
{
invoiceToFullName: "John Doe",
priceGross: 1600
},
]
}
}
var map = data.aaData.data.reduce(function(map, invoice) {
var name = invoice.invoiceToFullName
var price = +invoice.priceGross
map[name] = (map[name] || 0) + price
return map
}, {})
console.log(map)
var array = Object.keys(map).map(function(name) {
return {
fullName: name,
totalPriceGross: map[name]
}
})
console.log(array)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With