Reputation: 1101
I have an array of objects.
Objects looks like this:
0: Object
_id: "555baa9a034de05173e9fee4"
name: "Smirnoff Vodka"
number: 120
priceQuantity: 195
subtotal: 195
taxes: Array[0]
Now, from all the objects, I have to calculate sum of amount of total sale of every time so that I know the total sale amount of every item. .
i.e push the values in these arrays
itemAmount=[];
itemName=[];
The array is going to be very large therefore I need it to be very efficient at the same time.
Also, before the total amount is calculated, I have to iterate over the taxes array so that to add all the taxes. What could be the efficient way to do it?
Upvotes: 0
Views: 89
Reputation: 24276
You can try something like this:
var itemAmount = [], itemName = [];
myArray.map(function(obj){
var total = obj.subtotal;
for (var i = 0; i < obj.taxes.length; i++) {
total += obj.taxes[i];
}
var index = itemName.indexOf(obj.name);
if (index === -1) {
itemAmount.push(total);
itemName.push(obj.name);
} else {
itemAmount[index] += total;
}
});
Upvotes: 1
Reputation: 669
why dont you use the good things of javascript like dinamic allocation but the bad ones?
I would set an object for the products:
var Products = {}
And then set the entries like:
if(!products[WHATEVER])
products[WHATEVER] = [];
var temp = {};
temp.name = "asdf";
temp....
products[WHATEVER].push(temp);
so you have one products object where you can access just using id, name or whatever you want to any product, which is an array of the product entries.
Try it
Upvotes: 0
Reputation: 1382
If you need these values every time you open your application, it might be a good idea to not calculate these values, but to store them in your database. For every purchase, just adjust the totalSale value with the current price, and update totalSaleVAT with current price and VAT.
In addition to being a lot easier, doing it this way will give no false data when the prices change. Because the sold values won't be affected when the price rises or falls.
Upvotes: 0