1

I'm doing this code:

Class Cash
{
    constructor(v, q)
    {
     this.value = v;
     this.quantity = q;
    }

    var money = [];
    money.push( new Cash(50, 4);
    money.push( new Cash(20, 4);
    money.push( new Cash(10, 2);

i need to do this:

(money[0].value * money[0].quantity) + (money[1].value * money[1].quantity) + (money[n].value * money[n].quantity)

The expected result with the 3 arrays is 300 (50 * 4) + (20 * 4) + (10 * 2)

The idea is that no matter how many things i push into money it continues doing the sumproduct

I tried this, but doesn't work:

for (i = 0; i > money.length; i++)
{
    (money[i].value * money[i].quantity) + (money[i++].value * money[i++].quantity)
}
2
  • 1
    And to which variable do you want to add what you calculate in the loop? Why do you want to increment i 3 times per loop iteration? Commented Jun 8, 2021 at 20:41
  • 1
    Class should be class, there are three ) and one } missing, > should be < and currently the sum is not stored anywhere. If you fix all that it should work. Commented Jun 8, 2021 at 20:41

3 Answers 3

3

Simple for loop

var total = 0;
for( var i =0; i< money.length; i++) {
  total += money[i].value * money[i].quantity;
}
console.log(total);

or with reduce

const total = money.reduce(function (total, item) {
  return total + item.value * item.quantity;
}, 0);
console.log(total);
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly. Thanks
2

You can use the function Array.prototype.reduce as follow:

class Cash {
  constructor(v, q) {
    this.value = v;
    this.quantity = q;
  }
}

const money = [new Cash(50, 4), new Cash(20, 4), new Cash(10, 2)],
      result = money.reduce((a, m) => a + (m.value * m.quantity), 0);

console.log(result);

Comments

0

See the comments below for fixes.

class Cash { /* class, not Class */
  constructor(v, q) {
    this.value = v;
    this.quantity = q;
  }
} /* close your class declaration */

const money = [];
money.push(new Cash(50, 4)); /* close your parenthesis */
money.push(new Cash(20, 4)); /* close your parenthesis */
money.push(new Cash(10, 2)); /* close your parenthesis */

let sum = 0; /* initialize a sum variable with value 0 to retain results */
for (m of money) { /* or for (let i = 0; i < money.length; i++)
  /* Assign result of sum/product to something
   * More accurately add it to sum */
  sum += m.value * m.quantity;
}
console.log(sum);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.