Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create object with total value from associated string array and integer array

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}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading