Skip to content
Advertisement

Get total quantity for each unique product from a table with javascript

I have a resulting table from a backend that returns products and quantities. What i need to achieve is to check for repeating products and sum their quantities in a Overview below the table. I’ve written javascript, that partially works, but with more data i saw that it is not returning correct values and the summary shows too big numbers.

enter image description here

If you delete a chunk of html with rows from the table it works as expected, but cannot find the problem at this point. Also my code may not be the optimal to achieve what i need so any suggestions are welcome.

JavaScript
JavaScript

Advertisement

Answer

I’m assuming your requirement is to optimize the code to calculate the total for each product and display the total in the overview.

You can start with by getting the product total through looping each row, return an object data with product name as key and value as total e.g. { "Product 1": 10 }. Following example is achieve by using reduce():

JavaScript

By execute getProductTotals($('#product-list tbody tr')), you will get an object data which looks like this, key as product name and value as product total:

JavaScript

Then render the overview by using the object data. Loop through the object properties which is the product name and total, and append to overview:

JavaScript

Create a sync function, so every time you add or remove your row execute this function to update the overview:

JavaScript

Demo:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement