JSRB
JSRB

Reputation: 2613

Why does my plain JS loop not sum values to populate a new object?

I have an object which contains an array of ~130 objects which again have a field called orderProfit.
I now try to create a new object and populate it with the (chronological) sum of orderProfit.

Input (sample figures):

[{
    "trades": [
        {
        "fields": {
                "orderProfit": "100.000,00",
                [...]

        },
        },

        {
          "fields": {
                "orderProfit": "-500,00",
                [...]
        }
        },
        {
        "fields": {
                "orderProfit": "1.500,00",
                [...]
        }
        },

        [...]

}]

enter image description here

Desired output as array:

balanceByTrades = [100.000, 99.500, 101.000, ..., ]

Current attempt:

var balanceByTrades = [];
for (var i = 0; i < trades.length; i++) {
    trades[i].fields.orderProfit = parseFloat(trades[i].fields.orderProfit);
    // typeof returns number

    if (i == 0) {
        balanceByTrades[i] = trades[i].fields.orderProfit
    } else {
        balanceByTrades[i] = trades[i].fields.orderProfit + trades[i-1].fields.orderProfit
    }
}

Which outputs

balanceByTrades = [100.000,00, -500,00, 1.500,00]

So why it doesn't sum?

Upvotes: 0

Views: 41

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

When you need to parse a string to a number, don't use thousands separators, and to denote a decimal value, use a decimal point .

Remove all .s, and then replace the , with a .:

const arr = [{
  "fields": {
    "orderProfit": "100.000,00",

  }
}, {

  "fields": {
    "orderProfit": "-500,00",
  }
}, {

  "fields": {
    "orderProfit": "1.500,00",
  }
}];

const orderProfits = arr.map(({ fields }) => fields.orderProfit);
let currentBalance = 0;
const balanceByTrades = orderProfits.map((profitStr) => {
  const num = Number(
    profitStr.replace(/\./g, '').replace(',', '.')
  );
  currentBalance += num;
  return currentBalance;
});
console.log(balanceByTrades);

Upvotes: 3

Related Questions