WellNo WellNo - 1 year ago 57
Javascript Question

Add multiple numbers to Array

I have two arrays. They look like this:

array price = 14.60, 39.00


and

array quantity = 10, 5


(quantity is the quantity of items the user want to buy - 10 items from
productA
and 5 of
productB
)

Now I want loop through the variables to multiply the price with the quantity.

Like :

14,60 * 10


and

39,00 * 5


and add the two results to the
endPrice
variable.

I get the quantity array like this:

$('.quantity').change(function () {
quantitys = $('input[type=number]').map(function () {
return $(this).val();
}).get();
});


and the different prices like this:

var prices = $('.priceCell').map(function () {
return parseFloat($(this).html().trim());
}).get();


And that's what I tried:

var endPrice = 0;
for (var q = 0; q < quantitys.length; q++) {
for (var p = 0; p < prices.length; p++) {
endPrice = quantitys[q] * prices[p];
}
}

alert(endPrice);


Well, that haven't worked for me so well. Can someone help me there? Doesn't matter if the solution is pure JavaScript or jQuery.

Answer Source

1st problem

You were using nested loops thus every quantity would be multiplied by every prices. You only need one loop.

2nd problem

You were using endPrice = .... This will override the endPrice every time you go through this line. You need to use += that will add to the current enbPrice

var prices = [14.60, 39.00];
var quantities = [10,5];
var endPrice = 0;

for(let i=0, l=prices.length;i<l;i++){
  endPrice += prices[i] * quantities[i];  
}

console.log(endPrice);

EDIT

OP need to have separated totals. (See @David Thomas's answer)

You can use Array.prototype.map()

var prices = [14.60, 39.00];
var quantities = [10, 5];

var totals = prices.map((p, index) => p * quantities[index]);

console.log(totals);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download