I currently have an array of objects that looks like this:
const orders = [ { id: '1', userId: '3', total: 300 }, { id: '2', userId: '4', total: 200 }, { id: '3', userId: '5', total: 101 }, { id: '4', userId: '6', total: 80 }, { id: '5', userId: '7', total: 76 }, { id: '6', userId: '8', total: 44 }, { id: '7', userId: '9', total: 1000 }, { id: '8', userId: '10', total: 99 }, { id: '9', userId: '3', total: 65 }, { id: '10', userId: '4', total: 22 } ];
How would I combine the totals for any object in the array that shares the same userId?
I would like my outcome to look like this:
const newOrdersArray = [ { id: '1', userId: '3', total: 365 }, { id: '2', userId: '4', total: 222 }, { id: '3', userId: '5', total: 101 }, { id: '4', userId: '6', total: 80 }, { id: '5', userId: '7', total: 76 }, { id: '6', userId: '8', total: 44 }, { id: '7', userId: '9', total: 1000 }, { id: '8', userId: '10', total: 99 } ];
Advertisement
Answer
Try this:
const orders = [ { id: '1', userId: '3', total: 300 }, { id: '2', userId: '4', total: 200 }, { id: '3', userId: '5', total: 101 }, { id: '4', userId: '6', total: 80 }, { id: '5', userId: '7', total: 76 }, { id: '6', userId: '8', total: 44 }, { id: '7', userId: '9', total: 1000 }, { id: '8', userId: '10', total: 99 }, { id: '9', userId: '3', total: 65 }, { id: '10', userId: '4', total: 22 } ]; const totals = []; orders.forEach(x => { const obj = totals.find(o => o.userId === x.userId); if (obj) { obj.total = obj.total + x.total; } else { totals.push(x); } }); console.log(totals);