skip to Main Content

I have this code:

const my_transactions = [{amount: -100,currency: 'EUR'},{amount: -200,currency: 'EUR'},{amount: -400,currency: 'EUR'}];
let total = 0;
my_transactions.forEach(el => total = total - el.amount);
console.log('total:',total);

All the amounts are negative. I need to sum all the amounts and print out the balance.
As you can see, the balance is negative. It should print

-700

But the variable "total" gets a positive value. Why?

3

Answers


  1. Because subtracting a negative value is the same as adding a positive value.

    These produce the same result:

    console.log('subtracting:', 0 - (-100));
    console.log('adding:', 0 + (+100));

    If your intent is for all of these negative numbers to add up to -700 then add them instead of subtracting them:

    my_transactions.forEach(el => total = total + el.amount);
    
    Login or Signup to reply.
  2. This is a sum, not substractions

    const my_transactions = 
      [{amount: -100,currency: 'EUR'},
       {amount: -200,currency: 'EUR'},
       {amount: -400,currency: 'EUR'}];
       
    let total = 0;
    
    my_transactions.forEach(el => total += el.amount);
    
    console.log('total:', total);

    For shorter code:

    const my_transactions = 
      [ { amount: -100, currency: 'EUR' }
      , { amount: -200, currency: 'EUR' }
      , { amount: -400, currency: 'EUR' }
      ];
    let total = my_transactions.reduce((s,{amount:v}) => s + v, 0);
    
    console.log('total:', total);
    Login or Signup to reply.
  3. Simply change the minus (-) operator to the plus (+).

    Subtracting a negative number is the same as adding a positive number.

    const my_transactions = [
      { amount: -100, currency: 'EUR' },
      { amount: -200, currency: 'EUR' },
      { amount: -400, currency: 'EUR' }
    ];
    
    let total = 0;
    my_transactions.forEach(el => total = total + el.amount); // Change - to +
    
    console.log('Total:', total);

    A better approach is to reduce:

    const myTransactions = [
      { amount: -100, currency: 'EUR' },
      { amount: -200, currency: 'EUR' },
      { amount: -400, currency: 'EUR' }
    ];
    
    let total = myTransactions.reduce((sum, { amount }) => sum + amount, 0);
    
    console.log('Total:', total);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search