I would like to group an array of objects by Id
and sum the quantity in jQuery. How can I achieve this?
For example:
var array = [ { Id: "001", qty: 1 }, { Id: "002", qty: 2 }, { Id: "001", qty: 2 }, { Id: "003", qty: 4 } ]
Should result in:
[ { Id: "001", qty: 3 }, { Id: "002", qty: 2 }, { Id: "003", qty: 4 } ]
You can loop and sum it up
var array = [ { Id: "001", qty: 1 }, { Id: "002", qty: 2 }, { Id: "001", qty: 2 }, { Id: "003", qty: 4 } ]; var result = []; array.reduce(function(res, value) { if (!res[value.Id]) { res[value.Id] = { Id: value.Id, qty: 0 }; result.push(res[value.Id]) } res[value.Id].qty += value.qty; return res; }, {}); console.log(result)
Fiddle: Fiddle
var newArr = []; $.each(array,function(index,element){ if(newArr[element.Id]==undefined){ newArr[element.Id] =0; } newArr[element.Id] += element.qty; }); console.log(newArr);
Demo
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