I have a string array of product IDs, like this:
["A", "A", "B", "A"]
And another integer array of prices, like this:
[30, 50, 10, 40]
What would be the best way to produce a Javascript object with the unique item and its total cost, as the order of the integers are the prices associated with the same order of product numbers, so ideally it would return an object like this i.e.
{"A": 120, "B": 10}
Thank you!
I am relatively new to Javascript and SQL but I have tried using a foreach statement which I used successfully to produce a unique count of the item when I extract just that column into an array but not the problem as described above.
>Solution :
Simple reduce loop
const productIds = ["A", "A", "B", "A"];
const prices = [30, 50, 10, 40]
const totals = productIds.reduce((acc, key, index) => {
acc[key] = (acc[key] || 0) + prices[index];
return acc;
}, {});
console.log(totals);