I have the below js see this fiddle.
var name = ["Ted", "Sarah", "Nancy", "Ted", "Sarah", "Nancy"];
var prodID = [111, 222, 222, 222, 222, 222];
var prodName = ["milk", "juice", "juice", "juice", "juice", "juice"];
var qty = [1, 2, 3, 3, 3, 1];
var data = {};
for (i = 0; i < name.length; i++) {
if (!data[name[i]]) {
purchased = {
"name": name[i],
"prodID": prodID[i],
"prodName": prodName[i],
"qty": qty[i]
};
data[name[i]] = purchased;
} else {
purchased = data[name[i]];
purchased.qty += +qty[i];
}
data[name[i]] = purchased;
}
data = $.map(data, function (val, key) {
return val;
});
data.sort();
$.each(data, function (i, val) {
var plural = "";
if (val.qty > 1) {
plural = "'s";
}
$('body').append(val.name + ' has purchased ' + val.qty + ' bottle' + plural + ' of ' + val.prodName + '<br>');
});
Which outputs
Ted has purchased 4 bottle's of milk
Sarah has purchased 5 bottle's of juice
Nancy has purchased 4 bottle's of juice
What I want to do is show each of the products they have purchased and how many of each.
eg looking at the above Ted has purchased 1 milk and 3 bottle's of juice, but I am currently outputing Ted has purchased 4 bottle's of milk as 4 is the total qty of his purchases.
How can I group it by each prodID/ProdName so that I get the below.
Ted has purchased 1 bottle of milk and 3 bottle's of juice
Sarah has purchased 5 bottle's of juice
Nancy has purchased 4 bottle's of juice
purchasedis indeed an object. The remark was about the initial 4 arrays : you would be better off using one single array holding objects.