I’m trying to write a small piece of Javascript that will sort through a list of items in a shopping cart and determine whether the quantities for each brand sum to a multiple of 12.
An example of the shopping cart would be:
- Brand 1 - Oranges ---------- Qty: 10
- Brand 2 - Oranges ---------- Qty: 4
- Brand 1 - Oranges ---------- Qty: 2
- Brand 3 - Oranges ---------- Qty: 6
- Brand 2 - Oranges ---------- Qty: 20
The totals are therefore: Brand 1 = 12, Brand 2 = 24, Brand 3 = 6.
If the total of Brand 1, Brand 2 or Brand 3 is not a multiple of 12 (eg. Brand 3 above), I want the Javascript function to produce an error.
I think the best way to solve this is through an array and somehow splitting it based on brand then summing the totals but I’m not sure how to go about doing it.
Any help would be greatly appreciated.
You need two loops for that, the first one is to sum up all the qty’s for each brand, the 2nd loop is to check if all sums are a multiple of 12.
You can find an example here: http://jsfiddle.net/5QGWG/