First, make objects out of your arrays.
product_id = [4,5,1,3,5];
product_category_id =[2,2,1,3,2];
product_amount =[3000,4000,5000,5000,4000];
function Item(i,ci,a) {
this.id=i;
this.category_id=ci;
this.amount=a;
}
obj=[];
product_id.forEach((v,k)=>{obj.push(new Item(product_id[k],product_category_id[k],product_amount[k]))});
document.write(JSON.stringify(obj),'<br>');
document.write('<br>');
Then create two Map's, one for the id:amount pairing, and the other for the id:category relation.
Run through the amounts, and if the key already exists, add the new value to it. If not, update both Map's with the new key and respective value.
m=new Map(); m2=new Map();
obj.forEach(o=>{
if (m.has(o.id)) m.set(o.id,m.get(o.id)+o.amount);
else {
m.set(o.id,o.amount);
m2.set(o.id,o.category_id);
}
});
Finally, display the data, taking care to use the correct Map.
m.forEach((v,k)=>document.write(k+', '+m2.get(k)+', '+v,'<br>'));
Put it together:
product_id = [4,5,1,3,5];
product_category_id =[2,2,1,3,2];
product_amount =[3000,4000,5000,5000,4000];
function Item(i,ci,a) {
this.id=i;
this.category_id=ci;
this.amount=a;
}
obj=[];
product_id.forEach((v,k)=>{obj.push(new Item(product_id[k],product_category_id[k],product_amount[k]))});
document.write(JSON.stringify(obj),'<br>');
document.write('<br>');
m=new Map(); m2=new Map();
obj.forEach(o=>{
if (m.has(o.id)) m.set(o.id,m.get(o.id)+o.amount);
else {
m.set(o.id,o.amount);
m2.set(o.id,o.category_id);
}
});
m.forEach((v,k)=>document.write(k+', '+m2.get(k)+', '+v,'<br>'));